Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell - Use a function with unknown number of variables and other parameters

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?

like image 898
Nicola Cossu Avatar asked Mar 01 '11 04:03

Nicola Cossu


People also ask

How do I pass multiple parameters to a PowerShell function?

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.

What does $_ do in PowerShell?

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.

How do I create a parameterized function in PowerShell?

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.

What does $? Mean in PowerShell?

$? 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.


1 Answers

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.

like image 139
ravikanth Avatar answered Sep 29 '22 19:09

ravikanth