Im building a script but I cannot get it to complete, because im struggling getting the if
statement working.
$freespace = [math]::round((Get-WmiObject Win32_Volume -Filter "Label='User Disk'" | Foreach-Object {$_.FreeSpace})/ 1MB)
$volumespace = [math]::round((Get-WmiObject Win32_Volume -Filter "Label='User Disk'" | Foreach-Object {$_.Capacity})/ 1MB)
$usedspace=$volumespace-$freespace
Write-Host
"Used Space: $usedspace"
"Free Space: $freespace"
"Total Space Assigned: $volumespace"
if ($freespace -lt 5% $volumespace)
The if
statement needs to calculate like this (pseudo code):
if $freespace is less than 5% of the $volumespace
then my send mail command get attached to it.
I don't know how to make this calculation, despite struggling for hours.
答案 0 :(得分:1)
$freeSpace -lt $volumeSpace * .05
is the conditional you're looking for:
-lt
is PowerShells less-than operator (<
in other languages).5
(0.05
) represents 5% and is of type [double]
, the same as your variables.The following streamlined version of your code demonstrates use of a variable to store the percentage:
$freeSpace, $volumeSpace = Get-WmiObject Win32_Volume -Filter "Label='User Disk'" |
ForEach-Object { [math]::Round($_.FreeSpace / 1mb), [math]::Round($_.Capacity / 1mb) }
$usedSpace = $volumeSpace - $freeSpace
$thresholdPercentage = 5
# Send email if there's less than 5% free space.
# Note the need to divide the percentage number by 100.
# Alternatively, define $thresholdPercentage as 0.05 above.
if ($freeSpace -lt $volumeSpace * ($thresholdPercentage / 100)) {
# Send email
}