This PowerShell script checks the free disk space on the...
August 30, 2025 at 11:22 PM
This PowerShell script checks the free disk space on the system drive and compares it to a predefined minimum threshold. Here's what it does step-by-step:
-
Set Variables:
$Res = 0
: Initializes a result variable with a default value of0
.[UInt64]$MinDiskSpaceThreshold = 20 * 1024 * 1024 * 1024
: Sets the minimum disk space threshold to 20 GB, stored as a 64-bit unsigned integer.
-
Get System Drive and Available Space:
$SystemDrive = (Get-CimInstance Win32_OperatingSystem).SystemDrive
: Retrieves the system drive (e.g., "C:") using theWin32_OperatingSystem
class.$SystemDriveLetter = $SystemDrive[0]
: Extracts only the drive letter (e.g., "C").$SystemDriveSpace = (Get-Volume -DriveLetter $SystemDriveLetter).SizeRemaining
: Retrieves the remaining disk space on the system drive in bytes.
-
Print Current Space:
Write-Host 'Current system drive space:', $SystemDriveSpace.ToString('N0')
: Outputs the current remaining space with formatting for readability.
-
Check Space Against Threshold:
if ($SystemDriveSpace -lt $MinDiskSpaceThreshold)
: Compares the remaining disk space to the minimum required threshold (20 GB).- If the remaining space is less than 20 GB:
Write-Host 'System drive space is less than the threshold:', $MinDiskSpaceThreshold.ToString('N0'), 'Block Upgrade.'
: Prints a message that space is below the threshold, and further actions (like blocking an upgrade) might occur.$Res = 1
: Sets the result variable to1
to indicate insufficient space.
-
Error Handling:
catch { }
: If an error occurs (e.g., during system drive or space retrieval), it is silently ignored.
-
Print Final Result:
Write-Host 'Final result:', $Res
: Displays the final value of$Res
. If space is sufficient,$Res
remains0
; otherwise, it is1
.
Summary:
This code:
- Determines if the system drive has at least 20 GB of free space.
- If there is not enough space, it sets a flag (
$Res = 1
) and logs the issue. - It is designed to help decide whether to allow certain operations (e.g., system upgrades) based on available disk space.
Note: The ExecutionPolicy Restricted
part would prevent scripts from running, but this section appears tailored for informational or demo purposes.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node