Mar*_*ark 7 powershell if-statement function
鉴于此基本功能:
Function TestFunction {
Param ( [int]$Par1, [string]$Par2, [string]$Par3 )
If ($Par1 -ne $Null) { Write-Output "Par1 = $Par1" }
If ($Par2 -ne $Null -or $Par2 -ne '') { Write-Output "Par2 = $Par2" }
If ($Par3 -ne $Null) { Write-Output "Par3 = $Par3" }
}
TestFunction -Par1 1 -Par3 'par3'
Run Code Online (Sandbox Code Playgroud)
...输出是:
Par1 = 1
Par2 =
Par3 = par3
Run Code Online (Sandbox Code Playgroud)
即使我没有将任何内容传递给$Par2
变量,它仍然不是空或空.发生了什么,我怎样才能重写语句,以便第二个If语句计算为False并且脚本块不会被执行?
(我添加了-or $Par2 -ne ''
刚刚进行测试,无论有没有它都表现相同.)
iCo*_*dez 12
你在你的程序中的逻辑错误: $Par2
将始终不等于$null
或不等于''
.
要修复逻辑,您应该使用-and
而不是在-or
这里:
If ($Par2 -ne $Null -and $Par2 -ne '') { Write-Output "Par2 = $Par2" }
Run Code Online (Sandbox Code Playgroud)
但是,因为您将$Par2
参数转换为函数参数列表中的字符串:
Param ( [int]$Par1, [string]$Par2, [string]$Par3 )
^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
检查$Par2 -ne $Null
是不必要的,因为$Par2
将始终是类型字符串(如果您没有给它一个值,它将被分配给''
).所以,你应该写:
If ($Par2 -ne '') { Write-Output "Par2 = $Par2" }
Run Code Online (Sandbox Code Playgroud)
或者,因为''
评估为false,您可能只会:
If ($Par2) { Write-Output "Par2 = $Par2" }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
38698 次 |
最近记录: |