Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass multiple parameters into a function in PowerShell?

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty.

A quick test script:

Function Test([string]$arg1, [string]$arg2) {     Write-Host "`$arg1 value: $arg1"     Write-Host "`$arg2 value: $arg2" }  Test("ABC", "DEF") 

The output generated is

$arg1 value: ABC DEF $arg2 value:  

The correct output should be:

$arg1 value: ABC $arg2 value: DEF 

This seems to be consistent between v1 and v2 on multiple machines, so obviously, I'm doing something wrong. Can anyone point out exactly what?

like image 313
Nasir Avatar asked Feb 14 '11 01:02

Nasir


People also ask

How do you pass multiple parameters in PowerShell?

Refer below PowerShell script for the above problem statement to pass multiple parameters to function in PowerShell. Write-Host $TempFile "file already exists!" Write-Host -f Green $TempFile "file created successfully!" Write-Host -f Green $FolderName "folder created successfully!"

How do you pass multiple parameters to a function?

Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

How do you pass parameters to a function in PowerShell?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

How do I add multiple values to a variable in PowerShell?

In PowerShell, you can assign values to multiple variables by using a single command. The first element of the assignment value is assigned to the first variable, the second element is assigned to the second variable, the third element to the third variable, and so on. This is known as multiple assignment.


1 Answers

Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.

function foo($a, $b, $c) {    "a: $a; b: $b; c: $c" }  ps> foo 1 2 3 a: 1; b: 2; c: 3 
like image 57
x0n Avatar answered Oct 12 '22 05:10

x0n