Ed Palmer
Ed Palmer

Reputation: 55

I'm getting an error when I try to run PowerShell commands from a batch file

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?

Upvotes: 0

Views: 137

Answers (1)

JosefZ
JosefZ

Reputation: 30113

  • 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

Upvotes: 1

Related Questions