Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell function parameters syntax

Why do the Write-Host outside of the function work different than inside of the function?

It seems like somehow the parameters variables are changing from what I declared it to be...

function a([string]$svr, [string]$usr) {
    $x = "$svr\$usr"
    Write-Host $x
}

$svr = 'abc'
$usr = 'def'

Write-Host "$svr\$usr"  # abc\def
a($svr, $usr)           # abc def
like image 940
Shaunt Avatar asked Nov 15 '14 01:11

Shaunt


People also ask

How do you write 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.

How do you pass parameters to a PowerShell script?

Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.

What does %% mean in PowerShell?

% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.


1 Answers

Don't call functions or cmdlets in PowerShell with parentheses and commas (only do this in method calls)!

When you call a($svr, $usr) you're passing an array with the two values as the single value of the first parameter. It's equivalent to calling it like a -svr $svr,$usr which means the $usr parameter is not specified at all. So now $x equals the string representation of the array (a join with spaces), followed by a backslash, followed by nothing.

Instead call it like this:

a $svr $usr
a -svr $svr -usr $usr
like image 188
briantist Avatar answered Oct 19 '22 21:10

briantist