Powershell powercli在虚拟机';s数据存储区的可用空间超过%10

Powershell powercli在虚拟机';s数据存储区的可用空间超过%10,powershell,if-statement,snapshot,powercli,Powershell,If Statement,Snapshot,Powercli,嗨,我在写剧本好几天了。如果虚拟机的数据存储需要空间,我想使用虚拟机snashot 我的剧本: $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 $myar

嗨,我在写剧本好几天了。如果虚拟机的数据存储需要空间,我想使用虚拟机snashot

我的剧本:

$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”条件时,脚本总是对vm进行快照,不管可用空间百分比如何(我尝试了许多不同的数字,而不是原始的treshold)

İ如果我使用“-gt”条件,脚本永远不会使用snaphot,不管可用空间百分比如何

我还尝试了另一个脚本以获得相同的结果。同样,对于-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%" }'''

有什么问题,如何解决这个问题?

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

在该脚本因输出结果而失败之前,属性标签如下所示:

无法将“@{DSFreespace=16.12}”与“10.00”进行比较,因为对象 类型不同,或者对象“@{DSFreespace=16.12}”不相同 实现“IComparable”。第5行字符:5 +if(($dsfreespace-gt$treshold)){newsnapshot-vm$vm-name test123}else{ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +CategoryInfo:NotSpecified:(:)[],ExtendedTypeSystemException +FullyQualifiedErrorId:PSObject CompareTo

下面的更正代码解决了所有问题。它只接受结果值(在本例中为16.12),而不使用属性标签(DSFreespace)


如果将变量$Treshold更改为
$Treshold=10.00
,或者将变量$Treshold=10.00更改为[system.double]侧注,那么它是否有效;fir示例中的foreach非常奇特,但这可能是次要的。抱歉,没有任何更改:(Vm的数据存储目前有16%的可用空间。当我像你说的那样编辑和执行脚本时,它会拍摄快照。更改treshold值20、30或80不会改变任何东西。它仍然会拍摄快照。当我单独执行变量时,它们的值是:$myarray=get Vm test | get datastore | select object@{N=“DSFreespace”;E={[math]::Round($\.FreeSpaceGB)/($\.CapacityGB)*100,2)}DSFreespace-------16.14$Treshold=10.00-as[system.double]给出:10或$Treshold=“{0:n2}”-f 10给出;10.00我被卡住了:/
 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%" }
}