Home > Software engineering >  If disk space is less than twice of the file size then stop PowerShell script
If disk space is less than twice of the file size then stop PowerShell script

Time:07-02

I would like to write a script, where I check the disk space, check a file size (which I want to copy), and if the size of that file is at least twice as big as the free space, stop the script.

## How much free space
$VarSpace = $(Get-WmiObject -Class win32_logicaldisk | Where-Object -Property Name -eq C:).FreeSpace/1GB

## Exact file
$file = 'C:\Test\Folder1\TESZT.txt'
Write-Host((Get-Item $file).length/1GB)

if ($VarSpace ?????){break}
Copy-Item -Path "C:\Test\Folder1" -Destination "C:\Test\Folder2" -Recurse

CodePudding user response:

I think you should not convert space to GB - left it in bytes:

Clear-Host
## How much free space
$VarSpace = $(Get-WmiObject -Class win32_logicaldisk | Where-Object -Property Name -eq C:).FreeSpace

## Exact file
$file = 'C:\Test\Folder1\TESZT.txt'
$fileSpace = (Get-Item $file).Length

if($VarSpace -gt $fileSpace*2) {
    Write-Output "Enough space"
    Copy-Item -Path "C:\Test\Folder1" -Destination "C:\Test\Folder2" -Recurse
} else {
    Write-Output "Not enough space!"
    exit
}
  • Related