You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写PowerShell脚本仅返回首台超期快照VM适配Icinga状态码

看起来你是想做VM快照的过期检查,并且要对接Icinga监控返回不同状态码——只需要判断是否存在超过指定天数的快照,而不是列出所有符合条件的,这个需求很合理,毕竟监控系统只需要知道状态而不是全量列表。不过你给的第二个脚本有几个语法问题,我帮你修正并优化成适配Icinga的版本:

适配Icinga的VM快照过期检查脚本

首先修正原脚本的语法错误,同时调整逻辑来满足监控状态返回的需求:

# 自定义快照过期天数(这里设为3天,可按需修改)
$expiryDays = 3

# 获取首台存在过期快照的VM信息(只取第一个匹配项,提升效率)
$staleSnapshot = Get-Vm | Get-Snapshot | Where-Object { $_.Created -lt (Get-Date).AddDays(-$expiryDays) } | Select-Object -First 1 VM, Name, Created

# 根据检查结果返回对应Icinga状态
if ($staleSnapshot) {
    # 存在过期快照,返回CRITICAL状态(Icinga对应退出码2)
    Write-Host "CRITICAL: Found snapshot older than $expiryDays days on VM '$($staleSnapshot.VM.Name)'`nSnapshot Name: $($staleSnapshot.Name)`nCreated Time: $($staleSnapshot.Created)" -ForegroundColor Red
    exit 2
} else {
    # 无过期快照,返回OK状态(Icinga对应退出码0)
    Write-Host "OK: No snapshots older than $expiryDays days found" -ForegroundColor Green
    exit 0
}

关键说明

  • 原脚本的问题修正:原脚本里Get-Snapshot和Where之间缺少管道符,if语句直接跟在变量赋值后语法错误,且$vm.name的引用逻辑错误(需要从快照对象里关联的VM属性取值)
  • 为什么用Select-Object -First 1:完全符合你“仅检测首台符合条件VM”的需求,不用遍历所有快照,提升脚本执行效率,同时满足监控只需要知道“是否存在问题”的核心诉求
  • Icinga状态码对应:Icinga通过脚本的退出码识别监控状态,行业通用规则是0=OK、1=WARNING、2=CRITICAL,这里根据你的需求配置了对应状态码
  • 输出信息优化:返回的信息包含具体VM名称、快照名和创建时间,方便在Icinga控制台快速定位问题

扩展:支持多阈值告警

如果需要区分警告和严重状态(比如超过3天警告,超过7天严重),可以用这个版本:

$warningThreshold = 3  # 超过3天触发警告
$criticalThreshold = 7 # 超过7天触发严重告警

# 检查严重过期快照
$criticalSnapshot = Get-Vm | Get-Snapshot | Where-Object { $_.Created -lt (Get-Date).AddDays(-$criticalThreshold) } | Select-Object -First 1
# 检查警告级过期快照(仅当无严重快照时才检查)
$warningSnapshot = if (-not $criticalSnapshot) {
    Get-Vm | Get-Snapshot | Where-Object { 
        $_.Created -lt (Get-Date).AddDays(-$warningThreshold) -and $_.Created -ge (Get-Date).AddDays(-$criticalThreshold) 
    } | Select-Object -First 1
}

# 依次判断状态并返回
if ($criticalSnapshot) {
    Write-Host "CRITICAL: Found snapshot older than $criticalThreshold days on VM '$($criticalSnapshot.VM.Name)'" -ForegroundColor Red
    exit 2
} elseif ($warningSnapshot) {
    Write-Host "WARNING: Found snapshot older than $warningThreshold days on VM '$($warningSnapshot.VM.Name)'" -ForegroundColor Yellow
    exit 1
} else {
    Write-Host "OK: No stale snapshots found" -ForegroundColor Green
    exit 0
}

内容的提问来源于stack exchange,提问作者brauown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:57:27