I need to create a function. First variable must be an array with an unknown number of parameters plus another variable. My problem is that I don't know how distinguish between them.
I post an example:
function conc-str {
param([string[]]$array,[string]$name)
foreach($item in $array) {
$str+= $item
}
write-host $str
}
conc-str(@("aa","bb","cc"),"dd")
The result of this function is
aa bb ccdd
but as you can see I loop array elements and concatenate them. I thought to get just
aa bb cc
Where is my mistake?
To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
PowerShell uses the parameter value order to associate each parameter value with a parameter in the function. When you use positional parameters, type one or more values after the function name. Positional parameter values are assigned to the $args array variable.
$? Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed. For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.
The way you call it is:
conc-str @("aa","bb","cc") "dd"
You don't use "," as a parameter seperator in PowerShell. It is just a space. The moment you put a "," it becomes a single parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With