Powershell脚本第二个Where-Object无法输出预期结果问题排查
故障原因
- 过滤逻辑完全不匹配:你第二个
Where-Object {$_.State -like "$LDDCSRV"}语句的比对条件完全错误。$LDDCSRV是存储资源名称的变量,而集群资源的State属性返回的是Online、Offline、Failed这类状态枚举值,二者根本不可能匹配,该语句执行后只会返回空结果,自然无法输出预期的状态值。 - 冗余的二次过滤:你不需要两次调用
Where-Object,只要第一次过滤出名称匹配的资源对象后,直接读取该对象的State属性就能拿到状态值,不需要再次过滤。
修复方法
你可以直接调整逻辑,先定位目标资源再取属性,参考代码如下:
# 定义你要查询的资源名称变量 $LDDCSRV = "你的目标资源名称" # 一次过滤拿到目标资源对象 $targetClusterResource = Get-ClusterGroup -Cluster HV-CL01 | Where-Object {$_.Name -eq $LDDCSRV} # 构造输出对象转JSON,可自行添加需要的其他属性 $outputObj = [PSCustomObject]@{ ResourceName = $targetClusterResource.Name ResourceState = $targetClusterResource.State } $outputObj | ConvertTo-Json
如果需要兼容资源不存在的场景,可以增加判空逻辑:
$LDDCSRV = "你的目标资源名称" $targetClusterResource = Get-ClusterGroup -Cluster HV-CL01 | Where-Object {$_.Name -eq $LDDCSRV} if ($null -eq $targetClusterResource) { $outputObj = [PSCustomObject]@{ ResourceName = $LDDCSRV ResourceState = "NotFound" } } else { $outputObj = [PSCustomObject]@{ ResourceName = $targetClusterResource.Name ResourceState = $targetClusterResource.State } } $outputObj | ConvertTo-Json
注:如果确实需要模糊匹配,把-eq换回-like即可,同时注意给$LDDCSRV加通配符*。
内容的提问来源于stack exchange,提问作者SupremeFFS
相关产品推荐
相关产品推荐

