Reputation: 3
I'm currently on the middle of modifying a script, and I want to use $variable_expessions
like they way object properties are used:
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"
}
}
Upvotes: 0
Views: 463
Reputation: 46680
TessellatingHeckler's comment is right. You are defining calculated properties right and executing them correctly however you are not calling your properties correctly.
If you ran $volumes | Select-Object Label, $FreePerc, $TotalGB | Get-Member
you would see the properties you should be using. These are defined in your calculated property hashtable: "Capacity(GB)", "FreeSpace(GB)" and "Free(%)".
I simplified your function just to showcase the proper calling of the properties you were trying to interact with.
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{
$_
}
}
Still using Select-Object
the same way you were but then in the where clause I call the properties with their strings that you named.
If you really wanted to make your way work you would need to call the Name property of the hashtables. For instance....
Where-Object {$_.($FreePerc.Name) -le 50}
Upvotes: 1