首页 > 解决方案 > Powershell:在Switch语句中识别变量的名称

问题描述

我有以下代码片段:

$a = '1'
$b = ''

Switch ($a, $b) {
    {[string]::IsNullOrEmpty($_)} {
        Write-Host ("{0}: {1} is null." -f (Get-Date -Format s), $_)

        break
    }
    default {
        Write-Host ("{0}: {1} is not null." -f (Get-Date -Format s), $_)
    }
}

此 Switch 语句标识没有任何赋值的变量。当我运行它时,我希望能够告诉用户(或日志文件)哪个变量是空的,这可能吗?

生产代码有更多变量,它们通过调用各种 API 在整个脚本中定义。我宁愿避免一大堆 If/else 语句。

谢谢。

标签: powershellswitch-statement

解决方案


与其将变量值传递给 switch 语句,不如传递变量,并使用它Get-Variable -Value来获取守卫中的值。这看起来像

$a = '1'
$b = ''
$c = '3'
$d = '4'

Switch ('a', 'b', 'c', 'd') {
    {[string]::IsNullOrEmpty((Get-Variable -Value $_))} {
        Write-Host ("{0}: {1} is null." -f (Get-Date -Format s), $_)

        continue
    }
    default {
        Write-Host ("{0}: {1} is not null." -f (Get-Date -Format s), $_)
    }
}

另外 - 如果您希望switch语句遍历所有变量,那么您需要使用continue而不是break. 我在我的例子中做了这个改变。


推荐阅读