0

I made a powershell script that displays the disk size and free space in GB and percent. How to make a condition here, so that after reaching 51%, a message is displayed that there is not enough space?

$props = @(
    'DriveLetter'
    
    
    @{
        Name = 'SizeRemaining'
        Expression = { "{0:N2} GB" -f ($_.SizeRemaining/ 1Gb) }
    }
    @{
        Name = 'Size'
        Expression = { "{0:N2} GB" -f ($_.Size / 1Gb) }
    }
    @{
        Name = '% Free'
        Expression = { "{0:P}" -f ($_.SizeRemaining / $_.Size) }
    }
)

Get-Volume -DriveLetter C | Select-Object $props 


if ( $_.SizeRemaining -lt 50 )
{
    Write-Host "warning"
}
else {
    Write-Host ("ok")
}

1 Answer 1

4

You could just add another property to your output with the warning message in it. For example, add a Status property like this:

$props = @(
    'DriveLetter',    
    @{
        Name = 'SizeRemaining'
        Expression = { "{0:N2} GB" -f ($_.SizeRemaining/ 1Gb) }
    },
    @{
        Name = 'Size'
        Expression = { "{0:N2} GB" -f ($_.Size / 1Gb) }
    },
    @{
        Name = '% Free'
        Expression = { "{0:P}" -f ($_.SizeRemaining / $_.Size) }
    },
    @{
        Name = 'Status'
        Expression = { if(($_.SizeRemaining / $_.Size) -lt 0.5){"Low"}else{"OK"} }
    }
)

So, you can just do this to see all the information at once:

Get-Volume -DriveLetter C | Select-Object $props | Format-Table -AutoSize

Which gives output like this:

DriveLetter SizeRemaining Size      % Free Status 
----------- ------------- ----      ------ ------ 
          C 121.33 GB     464.14 GB 26.14% Warning

As it's just another property, you can access/manipulate it like any other property. For example, if you had lots of volumes on the system, you could just show the one with low space like this:

Get-Volume |
    Select-Object $props |
    Where-Object Status -eq 'Warning' |
    Format-Table -AutoSize
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.