如何将变量称为属性对象

时间:2017-03-22 01:31:06

标签: powershell powershell-v2.0

我目前正在修改脚本,我想像使用对象属性那样使用$variable_expessions

Function View-Diskspace {

##formating output
$TotalGB = @{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/ 1073741824),2)}}
$FreeGB = @{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace / 1073741824),2)}}
$FreePerc = @{Name="Free(%)";expression={[math]::round(((($_.FreeSpace / 1073741824)/($_.Capacity / 1073741824)) * 100),0)}}
Write-Host "`nGetting disk volume info from $machinename..." -ForegroundColor Cyan;
$volumes = Get-WmiObject -Class win32_volume -ComputerName localhost

#i want to detect $FreePerc with less than/or equal to 15 percent and volumes with no capacity, such as disc drives
if ($volumes | Select-Object Label, $FreePerc, $TotalGB | Where {$_.$FreePerc -le 15 -and $_.$TotalGB -ne 0})
{
    Write-Host "`nVolume(s) about to reach full capacity:"
    $volumes | Select-Object SystemName, DriveLetter, Label, $TotalGB, $FreeGB, $FreePerc | Where {$_.$FreePerc -le 15 -and $_.$TotalGB -ne 0} | Format-List
    Write-Host "Please initiate drive volume clean up."
}
else
{
    Write-Host "`n##> All volumes have more than 15% of free space"
}


}

1 个答案:

答案 0 :(得分:1)

TessellatingHeckler's comment is right。您正确定义计算属性并正确执行它们,但是您没有正确调用属性。

如果您运行$volumes | Select-Object Label, $FreePerc, $TotalGB | Get-Member,您会看到应该使用的属性。这些在您计算的属性哈希表中定义:“容量(GB)”,“FreeSpace(GB)”和“Free(%)”。

我简化了您的功能,只是为了展示您尝试与之交互的属性的正确调用。

Function View-Diskspace {

    # Calculated properties
    $TotalGB = @{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/ 1073741824),2)}}
    $FreeGB = @{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace / 1073741824),2)}}
    $FreePerc = @{Name="Free(%)";expression={[math]::round(((($_.FreeSpace / 1073741824)/($_.Capacity / 1073741824)) * 100),0)}}

    # Get WMI information and use calculated properties
    Get-WmiObject -Class win32_volume -ComputerName localhost | 
        Select-Object Label, $FreePerc, $TotalGB | 
        Where-Object {$_."Free(%)" -le 50 -and $_."Capacity(GB)" -ne 0} | 
        ForEach-Object -Begin {
            Write-Host "`nVolume(s) about to reach full capacity:"
        } -Process{
            $_
    }
}

仍然以同样的方式使用Select-Object但是在where子句中我使用你命名的字符串调用属性。

如果确实想要让自己的方式发挥作用,则需要调用哈希表的Name属性。例如......

Where-Object {$_.($FreePerc.Name) -le 50}