简体   繁体   English

在Powershell中将char数组的元素和字符串连接起来

[英]Concatenate elements of a char array and strings in powershell

I'm probably over thinking this, but this is not coming out the way I expect. 我可能会考虑过度,但这并没有达到我的预期。 I've searched google, I've searched stackoverflow. 我搜索过Google,搜索过stackoverflow。 Please Help. 请帮忙。

Here are some variables for testing, and the invocation of a function: 以下是一些测试变量和函数调用:

$SQL_FirstName = "PowerShell";
$SQL_LastName = "CreateUser";
$SQL_Office = "TEST";
$SQL_IsAdmin = $true;     
Create_User($SQL_FirstName.ToLower(), $SQL_LastName.ToLower(), $SQL_Office, $SQL_IsAdmin);

Here is the function, not much there yet: 这是函数,那里还不多:

Function Create_User([string]$FirstName, [string]$LastName, $Office, $IsAdmin)
{
    $FirstNameCharArray = [char[]]$FirstName;
    $UserName = [string]$FirstNameCharArray[0] + $LastName;
    Write-Host $UserName;
}

Now I expect the output to be "pcreateuser". 现在,我期望输出为“ pcreateuser”。 But it's not. 但事实并非如此。 I have tried casting different things, I have tried surrounding my variables with $(). 我尝试过强制转换其他内容,尝试使用$()包围变量。 I have tried using the + symbol and not using the + symbol. 我尝试使用+符号而不使用+符号。 I have tried smashing the variables right up against each other. 我已经尝试过将变量彼此对抗。 Every single time it just outputs "p". 每一次它只输出“ p”。

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

It's because of how you are calling the function. 这是因为您如何调用函数。 You are not supposed to use brackets for function calls nor use commas to separate the parameters (unless you are sending array values on purpose or subexpressions). 您不应该在函数调用中使用方括号,也不要在逗号之间使用逗号分隔参数(除非您是故意发送数组值或子表达式)。 You have passed it a single array of those elements. 您已将这些元素传递给它一个数组。

Create_User $SQL_FirstName.ToLower() $SQL_LastName.ToLower() $SQL_Office $SQL_IsAdmin

In your function call your sent an array to $firstname which was casted as a string "powershell createuser TEST True". 在函数调用中,您向$firstname发送了一个数组,该数组已转换为字符串“ powershell createuser TEST True”。 The other parameters would have been blank. 其他参数将为空白。 Hence your output. 因此,您的输出。

They work just the same as cmdlet calls. 它们的工作原理与cmdlet调用相同。 Just use spaces to separate the parameters and their values. 只需使用空格分隔参数及其值。

Get-ChildItem -Filter "*.txt" -Path "C:\temp"

String to char array 字符串到char数组

For what it is worth you don't need to cast the string as a char array. 对于什么是值得的,您不需要将字符串强制转换为char数组。 You can just use array notation directly on the string. 您可以直接在字符串上使用数组符号。

PS C:\Users\Matt> [string]"Bagels"[0]
B

Heck you don't even need to cast it "Bagels"[0] 哎呀,您甚至不需要将其投射为"Bagels"[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM