Powershell Function to Get Drive Size
Checking drive size, free space and occupied space for local server/computer is very easy, you can check through windows explorer, disk management and number of other ways but checking the same thing for remote server is difficult.
Here is a script which you can use to get drive size for local server/computer as well for remote server/computer. This script is having a function once executed a new cmdlet will be added in powershell.
How to use: Open notepad then copy below script text and paste it in notepad, Save notepad file on the name of customfunction and extension .ps1 a powershell script file. make sure notepad file is not saved as a .txt file extension, if it is then it will not execute.
Open Powershell and Run command (Get-Executionpolicy) to check execution policy of the system where this script need to be executed. if it is unrestricted then you can execute the same or else need to change execution policy with the powershell command (Set-Executionpolicy unrestricted) , A warning message will come press y to set the execution policy.
in powershell go to the location where the script is saved and execute the same by typing .\customfunction.ps1
Now powershell cmdlet is ready to use for all local/remote servers/computers.
Get-DriveSize localhost: This powershell command will list all system drives, Free space, Drive Size and %Free Space, to list the size of remote system just provide remote system name instead of localhost.
Get-DriveSize localhost c,d: This powershell command will list only c and d drive, free space, drive size and %free space.
function get-DriveSize{
param(
[parameter(mandatory = $true)]
$server,
$drive
)
if ($server -eq “”)
{
Write-Host “Please provide server name”
}
elseif($drive -eq $null)
{
gwmi win32_logicaldisk -computername $server | where-object {$_.drivetype -eq “3”} | format-table @{label=‘Server Name’; expression={$server}}, Deviceid, @{ label=‘Free space’; expression={$_.freespace/1gb}; f=“{0:N2} GB”},@{label=‘Drive Size’; expression={$_.size/1gb}; f=“{0:N2} GB”}, @{label=‘%Free Space’; expression={$_.freespace * 100/$_.size}; f=“{0:N2}”} -auto
}
else
{
$arr = @()
for($i=0; $i -lt $drive.Length; $i++)
{
$arr += ‘$_.deviceid -match ‘ + ‘”‘ + $drive[$i] + ‘”‘
}
$jn = $Arr -join ” -or “
$exp = ‘gwmi win32_logicaldisk -computername $server | where-object { ‘ + $jn + ‘} | format-table @{label=”Server Name”; expression={$server}}, Deviceid, @{ label=”Free space”; expression={$_.freespace/1gb}; f=”{0:N2} GB”},@{label=”Drive Size”; expression={$_.size/1gb}; f=”{0:N2} GB”}, @{label=”%Free Space”; expression={$_.freespace * 100/$_.size}; f=”{0:N2}”} -auto’
Invoke-Expression $exp
}