Appending/Concatenating 字符串参数
Appending/Concatenating String Arguments
我想执行如下命令:
# $IncludeTraits is a String[]
$exe = "C:\Foo.exe";
$traits;
foreach ($IncludeTrait in $IncludeTraits)
{
if ($IncludeTrait -ne $null -and $IncludeTrait -ne "")
{
$traits = $traits + "-trait `"$IncludeTrait`" "
}
}
& $exe $traits
最终命令应如下所示:
Foo.exe -trait "One" -trait "Two" -trait "Three"
如果我手动编写上面的命令它可以工作但不使用我的字符串连接代码。我怎样才能使用字符串连接使它工作?
不要使用字符串连接。将您的参数收集到一个数组中:
$traits = foreach ($IncludeTrait in $IncludeTraits) {
if ($IncludeTrait) { '-trait'; $IncludeTrait }
}
然后 运行 使用该数组的命令:
& $exe $traits
或使用splatting:
& $exe @traits
我想执行如下命令:
# $IncludeTraits is a String[]
$exe = "C:\Foo.exe";
$traits;
foreach ($IncludeTrait in $IncludeTraits)
{
if ($IncludeTrait -ne $null -and $IncludeTrait -ne "")
{
$traits = $traits + "-trait `"$IncludeTrait`" "
}
}
& $exe $traits
最终命令应如下所示:
Foo.exe -trait "One" -trait "Two" -trait "Three"
如果我手动编写上面的命令它可以工作但不使用我的字符串连接代码。我怎样才能使用字符串连接使它工作?
不要使用字符串连接。将您的参数收集到一个数组中:
$traits = foreach ($IncludeTrait in $IncludeTraits) {
if ($IncludeTrait) { '-trait'; $IncludeTrait }
}
然后 运行 使用该数组的命令:
& $exe $traits
或使用splatting:
& $exe @traits