Powershell 如何将变量作为属性对象调用

Powershell 如何将变量作为属性对象调用,powershell,powershell-2.0,Powershell,Powershell 2.0,我目前正在修改一个脚本,我想像使用对象属性一样使用$variable\u expressions: Function View-Diskspace { ##formating output $TotalGB = @{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/ 1073741824),2)}} $FreeGB = @{Name="FreeSpace(GB)";expression={[math]::round(($_.F

我目前正在修改一个脚本,我想像使用对象属性一样使用
$variable\u expressions

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"
}


}
。您正在正确定义计算属性并正确执行它们,但是您没有正确调用属性

如果运行
$volumes |选择对象标签,$FreePerc,$TotalGB | Get Member
,您将看到应该使用的属性。它们在计算属性哈希表中定义:“容量(GB)”、“自由空间(GB)”和“自由(%)”

我简化了您的函数,只是为了展示您试图与之交互的属性的正确调用

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{
            $_
    }
}
仍然使用与您相同的方法
selectobject
,但在where子句中,我使用您命名的字符串调用属性

如果您真的想让您的方式工作,您需要调用哈希表的Name属性。例如

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

$.$FreePerc
-酒店名称不是
$FreePerc
,而是
$.“Free(%)”
(和
容量(GB)
)感谢您的回复。我试过了,但没用。我甚至试着用变量和属性名来比较结果:PS P:\>$volumes |选择对象$FreePerc Free(%)----87 PS P:\>$volumes |选择对象“Free(%)”Free(%)----谢谢!我使用了你提供的第二个选项。