6

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

1 Answer 1

15

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
2
  • 4
    I use Powershell every day, and every now and then I make this exact mistake and spend 10+ minutes pulling my hair out.
    – briantist
    Commented Nov 19, 2014 at 6:56
  • 2
    Oh and I want to point out that using Set-StrictMode will help you catch this mistake.
    – briantist
    Commented Nov 19, 2014 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.