C. Kellerman
C. Kellerman

Reputation: 3

What's wrong with this line of code in my batch script?

I'm trying to assign the freespace on Disk C: to a variable using this command, and I can't seem to get it to function at properly.

For /f "tokens=3" %%A IN ('powershell -noprofile -command "get-WmiObject win32_logicaldisk -Filter \"DeviceID = 'C:'"" ^| Find "FreeSpace"') DO Set _FreeSpace=%%A

It doesn't assign the variable anything. When running the powershell script directly inside of the ISE, it gives the expected result. And running the code in the parentheses inside of CMD directly (changing the ^| to |) works fine as well.

I'm sure I'm missing something obvious as this is my first time really getting into For commands, but any assistance would be greatly appreciated!

Upvotes: 0

Views: 214

Answers (3)

aschipfl
aschipfl

Reputation: 34979

Since = is a standard token separator in cmd.exe just like the SPACE you need to properly escape it (note that \ is nothing special to cmd.exe so the = appears unquoted):

for /F "tokens=3" %%A in ('powershell -noprofile -command "get-WmiObject win32_logicaldisk -Filter \"DeviceID ^= 'C:'\"" ^| Find "FreeSpace"') do set "_FreeSpace=%%A"

Upvotes: 1

Compo
Compo

Reputation: 38719

I would offer this alternative, which will additionally provide the result in GB:

@For /F "Delims=" %%G In ('Powershell -NoP^
 "gWMI Win32_LogicalDisk -F \""DeviceID='C:'\""|"^
 "%%{[Math]::Round($_.FreeSpace/1GB,2)}"'
)Do @Set "FDS=%%G"
@Echo Freespace on C: is %FDS%GB
@Timeout -1

or the simpler:

@For /F "Delims=" %%G In ('Powershell -NoP^
 "[Math]::Round($(gWMI Win32_LogicalDisk -F \""DeviceID='C:'\"").FreeSpace/1GB,2)"
')Do @Set "FDS=%%G"
@Echo Freespace on C: is %FDS%GB
@Timeout -1



Based upon your comment, if you want it in bytes, you could use:

@For /F "Delims=" %%G In ('Powershell -NoP^
 "gWMI Win32_LogicalDisk -F \""DeviceID='C:'\""|Select -Exp FreeSpace"
')Do @Set "FDS=%%G"
@Echo Freespace on C: is %FDS%bytes
@Timeout -1

or the simpler:

@For /F "Delims=" %%G In ('Powershell -NoP^
 "(gWMI Win32_LogicalDisk -F \""DeviceID='C:'\"").FreeSpace"
')Do @Set "FDS=%%G"
@Echo Freespace on C: is %FDS%bytes
@Timeout -1

Upvotes: 0

avery_larry
avery_larry

Reputation: 2135

Hard to get all those single and double quotes to work with powershell and then inside a for loop. This seems to work for me:

setlocal enabledelayedexpansion
set "_cmdToRun=powershell -noprofile -command "get-WmiObject win32_logicaldisk -Filter \"DeviceID = 'C:'"""
For /f "tokens=3" %%A IN ('!_cmdToRun! ^| Find "FreeSpace"') DO Set _FreeSpace=%%A

Upvotes: 2

Related Questions