powershell - 如果 vm 的数据存储有超过 %10 的可用空间,powercli 创建快照
问题描述
嗨,我正在处理一个脚本好几天。如果 vm 的数据存储区需要空间,我想获取 vm 快照。
我的脚本:
$myarray =@{}
$myarray = get-vm test | get-datastore | select-object @{N="DSFreespace"; E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}}
$Treshold = "{0:n2}" -f 10
foreach ($Treshold in $myarray) {
if ($myarray -ge $Treshold){new-snapshot -vm test -name test123} else {
Write-Host "You cannot take a snapshot. Datastore free spce is lower than 10%" }
}
当我在 shell 中运行脚本时,我也为同一件事编写了另一个脚本,但没有运气。当我使用“-ge”条件时,脚本总是拍摄虚拟机的快照,无论可用空间百分比(我尝试了许多不同的数字,除了原始阈值)
如果我使用“-gt”条件,脚本从不拍摄快照,无论可用空间百分比。
我还尝试了另一个脚本来获得相同的薄而相同的结果。此外,对于 -lt 和 -le 条件也是如此
$vm = get-vm test
$Treshold = "{0:n2}" -f 10
$DSFreespace = get-vm $vm| get-datastore | select-object @{N="DSFreespace"; E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}}
if($DSFreespace -ge $Treshold){new-snapshot -vm $vm -name test123} else {
Write-Host "You cannot take a snapshot. Datastore free space is lower than 10%" }'''
出了什么问题,如何解决这个问题?
解决方案
我通过添加| Select-Object -ExpandProperty DSFreespace
到 $dsfreespace 参数解决了问题。
在该脚本由于输出结果而失败之前,属性标签为:
无法将“@{DSFreespace=16.12}”与“10.00”进行比较,因为对象类型不同或对象“@{DSFreespace=16.12}”未实现“IComparable”。在 line:5 char:5 + if (($dsfreespace -gt $treshold)) {new-snapshot -vm $vm -name test123} else { + ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException + FullyQualifiedErrorId : PSObjectCompareTo
如下更正代码解决了所有问题。它只需要结果值(在本例中为 16.12),而不需要属性标签(DSFreespace)
ForEach ($vm in (get-datastore -VM $vm) | ForEach {$_.VM}) {
$vm = get-vm test
$treshold = "{0:n2}" -f 10
$dsfreespace = get-datastore -VM $vm | select-object @{N="DSFreespace"; E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}} | Select-Object -ExpandProperty DSFreespace
if (($dsfreespace -gt $treshold)) {new-snapshot -vm $vm -name test123} else {
Write-Host "You cannot take a snapshot. Datastore free space is lower than 10%" }
}
推荐阅读
- mysql - EF .NET Core 5 异常中的 LINQ 表达式“OUTER APPLY 投影映射”
- c - 为什么我不能设置结构
- function - 使用map和foldr、haskell实现功能
- c - switch case 中的另一种情况
- swiftui - SwiftUI 侧边栏不记得屏幕
- python - 如何在字典初始化时调用 __set_item__?
- docker - 将 Verdaccio Registry 与 Skaffold 一起使用
- c# - 如何在不编辑视图的情况下在 WPF MVVM 中生成网格的行和列?
- javascript - Javascript一次选择所有选项
- python - 检查车辆停放了多长时间