powershell测试尚未分配的变量

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取决于变量是否存在.

  • @ruffin`Test-path变量:ProgramName`将返回`$ true`或`$ false`.严格模式的好处.我补充说. (4认同)
  • 我不认为*适用于`Set-StrictMode -version最新;`,对吗?当严格模式开启时,您应该如何检查它?**编辑**显然[`Test-Path变量:global:foo`](http://stackoverflow.com/a/3163008/1028230) (2认同)
  • 此答案包含最常见的 PowerShell 陷阱之一,即相等运算符在数组上工作的反直觉方式(请参阅 [Microsoft Docs](https://learn.microsoft.com/en-us/powershell/scripting/learn /deep-dives/everything-about-arrays#-eq-and--ne))。本质上,如果“$ProgramName”恰好是一个以“$null”作为其所有值的数组,则该语句将返回“$false”,尽管该变量不为空(即数组)。解决方法是简单地通过将 $null 放在左侧来切换比较:“If ($null -ne $ProgramName)” (2认同)

Dav*_*ant 10

Test-Path variable:\var 我猜你应该做你想做的事.

  • 这是真正正确的答案.另一种方法是技术上的黑客攻击.这是执行此操作的预期编程方式. (3认同)

Jas*_*ton 5

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...


js2*_*010 5

除了 -is 不适用于类型这一事实之外,在 powershell 7 中还有一个用于此目的的新运算符。仅当左侧为 $null 时才会进行赋值。

$programname ??= 'foo'
Run Code Online (Sandbox Code Playgroud)