0

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?

3
  • I'm not familiar with batch files, I find them a pain to work with. You could create a string with all of your PowerShell commands and then execute that string with Invoke-Expression. I would rather do this than having to deal with escaping stuff. Commented Apr 16, 2021 at 20:15
  • EXIT is 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 the SELECT-OBJECT command thinks EXIT is a parameter for itself. Commented Apr 16, 2021 at 20:18
  • When you chose to use the escape character to put all of your Powershell code on multiple lines it thinks EXIT is 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. Commented Apr 16, 2021 at 20:25

1 Answer 1

1
  • use ; semicolon as Powershell command separator;
  • use another kind of escaping quotes (double quotes are choked down);
  • you can use an integer in Exit.

The code:

@echo OFF Powershell -nopro $disk = Get-WmiObject Win32_LogicalDisk -Filter """"DeviceID='D:'"""" ^| Select-Object Freespace; ^ Write-Host (""""{0}GB free"""" -f [math]::round($disk.FreeSpace / 1GB)) -Fore Yellow; ^ Exit ([math]::truncate($disk.freespace / 1GB)) set FreeSpace=%errorlevel% echo %FreeSpace% 

Output: .\SO\67131203.bat

796GB free 796 
Sign up to request clarification or add additional context in comments.

1 Comment

Ah. Your solution set the DeviceID to D: and changing it to C: works. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.