如果虚拟机的数据存储具有超过%10的可用空间,则powercli创建快照

问题描述 投票:0回答:1

[嗨,我正在研究脚本好几天了。如果虚拟机的数据存储区需要空间,我想使用虚拟机快照。

我的脚本:

$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%" }'''

怎么了,怎么解决这个问题?

powershell if-statement snapshot powercli
1个回答
0
投票

我通过在$ dsfreespace参数中添加| Select-Object -ExpandProperty DSFreespace解决了问题。

在该脚本由于输出结果而失败之前,属性标签为:

无法将“ @ {DSFreespace = 16.12}”与“ 10.00”进行比较,因为对象类型不同或对象“ @ {DSFreespace = 16.12}”不同实施“ IComparable”。在线:5字符:5+ if((($ dsfreespace -gt $ treshold)){new-snapshot -vm $ vm -name test123} else {+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo:未指定:(:) [],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%" }
}
© www.soinside.com 2019 - 2024. All rights reserved.