I just want to concatenate with args string but I get -System.Object[] in $test instead of "testapp" if args is app:
function test {
Write-Host $args;
$test = -join("test",$args.ToString());
Write-Host $test;
}
CodePudding user response:
The easiest way is to use string interpolation:
function test {
Write-Host $args
$test = "test$args"
Write-Host $test
}
test app
Output:
app
testapp
String interpolation joins the array values using the space character by default.
To specify a custom separator string, use the -join
Operator like this:
function test {
Write-Host $args
$argsJoined = $args -join ', '
$test = "test $argsJoined"
Write-Host $test
}
test 4 8 15
Output:
4 8 15
test 4, 8, 15
As for what you have tried:
$test = -join("test",$args.ToString());
$args
is an array, whose ToString()
method only returns the type name of the array.
As Theo pointed out in his helpful comment, you could make that work by using array concatenation:
$test = -join(@("test") $args)
The array sub-expression operator @
ensures that the
operator applies to an array, instead of the string "test"
.
Slightly shorter variant:
$test = -join @("test"; $args)
Note the use of ;
to turn $args
into a sub-expression, which effectively unrolls it.
In both cases the argument of the -join
operator is a new array that is a combination of "test"
and the elements of the $args
array.