I have an existing batch file. I need to show free space on C:. The best method I have found is to use PowerShell.
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object FreeSpace Write-Host ("{0}GB free" -f [math]::truncate($disk.FreeSpace / 1GB)) I can modify this by exiting with the result in errorlevel.
Powershell:
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object Freespace Exit ("{0}" -f [math]::truncate($disk.freespace / 1GB)) After exiting PS:
set FreeSpace=%errorlevel% echo %FreeSpace% And that works perfectly when I run it from command prompt. To make it work from a batch file, I need to escape a few characters.
Powershell $disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID=`'C:`'" ^| Select-Object Freespace ^ Exit ("{0}" -f [math]::truncate($disk.freespace / 1GB)) set FreeSpace=%errorlevel% echo %FreeSpace% But I get the error:
Select-Object : A positional parameter cannot be found that accepts argument 'Exit'. It's as if Select-Object is parsing the next line. Any ideas what I am doing wrong?
EXITis another command. When you want to run multiple commands on one line you need to separate the commands by a semi-colon. As it stands theSELECT-OBJECTcommand thinksEXITis a parameter for itself.EXITis part of the previous line. You can't have all your powershell code on multiple lines without using the escape character. So you still need to follow the syntax of running multiple commands on one line by using the semicolon.