Get-vm where {_.created.仅列出第一次出现早于 xxx 的快照

Get-vm where {_.created. Only list the first occurence of snapshot older than xxx

我想检查超过特定天数的虚拟机快照。第一个脚本列出所有符合该条件的虚拟机。

$Snapshots = Get-Vm | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-3)} | Select-Object VM, Name, Created

因为此脚本仅显示第一次出现的符合条件的虚拟机。

$Snapshots = Get-Vm | Get-snapshot where {$_.Created -lt (Get-Date).AddDays(-3)} | Select-Object VM, Name, Created

if ($Snapshots.count -gt 0) {
    Write-Host "Found snapshots older than X!", $vm.name -ForegroundColor Yellow

}
else {
    Write-Host "Found no snapshots older than X!" -ForegroundColor Green
}

我之所以要像第二个例子那样做,是因为我需要向 Icinga 发送不同的状态码。

你使用了错误的变量

$vm.name

改用:

$Snapshots.vm.Name
$Snapshots.Name

或所有行

Write-Host "Found snapshots older than X!", $Snapshots -ForegroundColor Yellow

如果我们假设 $Snapshots 包含您需要的数据,那么它将是一个集合。您可以使用索引 [0] 从该集合中有选择地挑选一个元素并显示其属性 ($Snapshots[0].VM.Name).

$Snapshots = Get-Vm | Get-Snapshot |
    Where Created -lt (Get-Date).AddDays(-3) |
        Select-Object VM, Name, Created

if ($Snapshots.Count -gt 0) {
    Write-Host "Found snapshots older than X!", $Snapshots[0].VM.Name -ForegroundColor Yellow

}
else {
    Write-Host "Found no snapshots older than X!" -ForegroundColor Green
}