PowerShell function parameters syntax

荒凉一梦 提交于 2020-12-26 06:55:36

问题


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'
$x = "$svr\$usr"
Write-Host $x
a($svr, $usr)

Results…

abc\def

abc def\


回答1:


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


来源:https://stackoverflow.com/questions/26941644/powershell-function-parameters-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!