如何将PowerShell中PSCustomObject结果存入单变量并整合多字段
优化NetScaler组件状态检测脚本,统一收集告警信息
需求
调整现有PowerShell脚本,实现以下目标:
- 筛选出状态值连续两次为
0.0的NetScaler组件 - 将组件的
NetscalerName、Componentname、Name字段封装为PSCustomObject - 把所有符合条件的异常组件统一存入一个变量,便于后续遍历发送NOC告警
修改后的脚本
function Get-NSVIPStatus { # 初始化存储异常结果的数组 $VIPResults = @() $Components = @("virtualserver", "services", "servicegroup", "contentswitch") foreach ($component in $Components){ try { $Metrics = Invoke-RestMethod "https://graphvip100.com/metrics/find?query=metrics.winops.netscalers.components.nsexsre*.$component.*.2m.status" -ErrorAction Stop $Raw = foreach ($metric in $Metrics) { Invoke-RestMethod "https://graphvip100.com/render?target=$($metric.id)&from=-10min&format=csv" -ErrorAction Stop } $Data = $Raw | ConvertFrom-Csv -Header "Metric","Time","Value" | Where-Object { -not [string]::IsNullOrEmpty($_.Value) } | Group-Object -Property Metric foreach ($group in $Data) { $NetscalerName = $group.Name.Split(".")[4] $Componentname = $group.name.split(".")[5] $Name = $group.Name.Split(".")[6] # 筛选连续两次状态为0.0的组件,同时排除指定模式和匹配排除规则的实例 If (($group.Group[-1].Value -eq "0.0") -and ($group.Group[-2].Value -eq "0.0") -and ($name -notmatch $exclusionpattern) -and ($netscalername -match $netscalerexclusion)) { # 将异常组件信息加入结果数组 $VIPResults += [PSCustomObject]@{ NetscalerName = $NetscalerName Componentname = $Componentname Name = $Name } } ElseIf (($group.Group[-1].Value -eq "1.0") -and ($group.Group[-2].Value -eq "1.0") -and ($name -notmatch $exclusionpattern) -and ($netscalername -match $netscalerexclusion)) { Write-Verbose "$(Get-Date): $NetscalerName $Componentname $Name 状态正常(UP)" -Verbose } ElseIf (($group.Group[-1].Value -eq "2.0") -and ($group.Group[-2].Value -eq "2.0") -and ($name -notmatch $exclusionpattern) -and ($netscalername -match $netscalerexclusion)) { Write-Verbose "$(Get-Date): $NetscalerName $Componentname $Name 状态为OUT OF SERVICE" -Verbose } } } catch { Write-Error "获取组件状态时出错: $_" throw $_ } } # 返回所有异常结果,若无异常则返回空数组 return $VIPResults }
脚本说明
- 封装为
Get-NSVIPStatus函数,符合预期调用方式 - 用数组
$VIPResults统一存储所有异常组件信息,避免原脚本中变量被覆盖的问题 - 增加
try/catch块捕获请求过程中的错误,便于排查问题 - 优化Verbose输出,增加时间戳,便于日志回溯
使用示例
Try{ $VIPResults = Get-NSVIPStatus } Catch{ Throw $_ } if ($null -ne $VIPResults -and $VIPResults.Count -gt 0) { foreach ($R in $VIPResults) { Write-Verbose "$(Get-Date): 发送NOC告警: EXSRE Netscaler $($R.Name) ($($R.Componentname)) 在 $($R.NetscalerName) 上已下线" -Verbose # 此处可添加实际告警发送逻辑,例如调用邮件API、短信接口等 } }
内容的提问来源于stack exchange,提问作者saravana raj
相关产品推荐
相关产品推荐

