为什么函数外部的Write-Host与函数内部的工作方式不同?
似乎某种程度上参数变量正在从我声明的变化......
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)
结果...
ABC \ DEF
abc def \
为什么函数外部的Write-Host与函数内部的工作方式不同?
似乎某种程度上参数变量正在从我声明的变化......
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)
结果...
ABC \ DEF
abc def \
1 回答
不要使用括号和逗号调用powershell中的函数或cmdlet(仅在方法调用中执行此操作)!
当你调用
a($svr, $usr)
时,你're passing an array with the 2 values as the single value of the first parameter. It'等效于调用它a -svr $svr,$usr
,这意味着根本没有指定$usr
参数 . 所以现在$x
等于数组的字符串表示形式(带空格的连接),后跟反斜杠,后面没有任何内容 .而是像这样称呼它: