I need to write a power-shell script, where if the free disk space is more than 50GB, then -"do something", else exit the script - do nothing.
For that I am trying to save the free disk space value in a $var
and play with an if-else
in my script, something like:
$var = <parse disk space free from Get-PSDrive C output>
if ($var -ge 50) {
#Do something
}
else {
#Do nothing
}
I tried this so far:
$var = Get-PSDrive C -psprovider Filesystem | select-object @{Name="Free"; Expression={$_.Free/1GB}}
But printing the $var
gives me: @{Free=112.352230072021}
, but what I wanted is 112
, i.e just the free disk-space value , rounded off to anything before the decimal.
What needs to be done ? is there any Unix
style awk
or sed
to parse outputs in power-shell ?
CodePudding user response:
The Free
property on a PSDrive is in Bytes. It's very much straightforward to take the drive(s) where it exceeds a certain number, no need to calculate anything, no need for variables, no need for if
/else
:
Get-PSDrive C -PSProvider FileSystem | where Free -gt 50GB | foreach {
Write-Host $_
# do something
}
50GB
is a PowerShell built-in convenience shorthand for 50 * 1073741824
. Other such shorthands (KB
, MB
, TB
, PB
) exist.
CodePudding user response:
if you REALLY want to use an if/else
structure, then this would work. [grin]
the code ...
$TargetDisk = 'c'
$MinDiskFree_GB = 50
# uncomment the line below to show the "too small" error msg
#$MinDiskFree_GB = 5000
$ActualDiskFree_GB = [math]::Round((Get-PSDrive -Name $TargetDisk).Free / 1gb, 2)
if ($ActualDiskFree_GB -gt $MinDiskFree_GB)
{
Write-Host ('Drive [ {0} ] has enuff free space. [ {1} GB]' -f $TargetDisk, $ActualDiskFree_GB)
}
else
{
Write-Warning (' Drive [ {0} ] does not have enuff free space. [ {1} GB]' -f $TargetDisk, $ActualDiskFree_GB)
}
output with each of the two test values ...
Drive [ c ] has enuff free space. [ 845.77 GB]
WARNING: Drive [ c ] does not have enuff free space. [ 845.77 GB]
what it does ...
- defines the variables
if you need to run this more than once, it would likely work better as a function with parameters. - gets the free space in GB
- compares the actual versus the minimum desired free GB
- does the appropriate thing