powershell - 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 语句。
谢谢。
解决方案
与其将变量值传递给 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
. 我在我的例子中做了这个改变。
推荐阅读
- ssl - TLS 握手如何在负载平衡系统中工作?
- javascript - 返回输出函数javascript内部html
- swift - 使用 Metal Framework 将图像保存到磁盘时,命令缓冲区的执行被中止/GPU 错误
- css - 完整日历默认视图
- android - Cognito 用户池 - 缓存的用户 ID
- python - Django GenericRelation 递归导入
- tensorflow - 如何使用 estimator API 在 tensorboard 上添加更多细节
- java - java - 如何在不使用Java延迟的情况下监控完整的文件传输
- angular - 无法实例化循环依赖!HTTP_INTERCEPTORS ("[ERROR ->]"):在 NgModule CoreModule 中
- ajax - 我的 ajax 数据从视图发送到处理程序的范围存储在冷箱中