res*_*101 18 variables powershell if-statement conditional-statements
我想测试是否已为变量分配了变量,如果没有执行操作.怎么能实现呢?
我尝试使用以下代码但收到错误:'-is'的右操作数必须是一个类型.
此时未分配$ ProgramName.
If ($ProgramName -isnot $null) {
$ProgramName = $ProgramName + ', ' + $cncPrograms
}
Else {
If ($cncPrograms -isnot $null) {
$ProgramName = $cncPrograms
}
}
Run Code Online (Sandbox Code Playgroud)
JNK*_*JNK 38
任何未分配的变量的值都为null,而不是null的数据类型.所以,就这样做:
If ($ProgramName -ne $null)
Run Code Online (Sandbox Code Playgroud)
... TRUE
如果已将其分配给非空值,则返回.
更简单的检查是
IF($ProgramName)
Run Code Online (Sandbox Code Playgroud)
哪个会检查是否存在$null
,虽然逻辑是相反的,所以你可以使用
IF(!$ProgramName)
Run Code Online (Sandbox Code Playgroud)
编辑:
Ruffin在评论中提出了关于strictmode的一个好点.这个方法也可以:
Test-Path variable:ProgramName
或者,Test-Path variable:global:ProgramName
如果它明确地是全局范围的,例如.这将返回$true
或$false
取决于变量是否存在.
Contrary to answers above
Test-Path variable:ProgramName
Run Code Online (Sandbox Code Playgroud)
Might not be what you are looking for because it only tests for the existence of the variable. If the Variable is set to $null it will still return $true.
Therefore in strictmode you may have to test for it's existence existence and whether it is non-empty.
Set-StrictMode -version Latest
#TODO Add a scope parameter
Function IsEmpty([string]$varname){
if (Test-path "variable:$varname"){
$val=(gi "variable:$varname").value
if ($val -is [bool]) {$false}
else {$val -eq '' -or $val -eq $null} }
else{ $true }
}
#TEST:
if (test-path variable:foobar){remove-variable foobar} ; IsEmpty foobar
$foobar=$null; IsEmpty foobar
$foobar=''; IsEmpty foobar;
$foobar=$false; IsEmpty foobar
#Results:
True
True
True
False
Run Code Online (Sandbox Code Playgroud)
Strict mode kind of takes some of the fun out of scripting...
除了 -is 不适用于类型这一事实之外,在 powershell 7 中还有一个用于此目的的新运算符。仅当左侧为 $null 时才会进行赋值。
$programname ??= 'foo'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
39781 次 |
最近记录: |