Love to get the output of powershell script in a variable to use in a batch file

Viewed 241

I have the follow "powershell script"

Get-WMIObject -Query "SELECT * from win32_logicaldisk WHERE DriveType = '3'" | Measure-Object -Property Size -Sum | select -ExpandProperty SUm

And i want to use this to make it happen, but my var variable is empty. I think it's with the " or ' but i'm a newbie and my knowledge isn't that great with scripting. Can someone help me with this silly thing?

FOR /F "tokens=* USEBACKQ" %%F IN (`powershell -noprofile {Get-WMIObject -Query "SELECT * from win32_logicaldisk WHERE DriveType = '3'" | Measure-Object -Property Size -Sum | select -ExpandProperty SUm}`) DO (
SET var=%%F
2 Answers

The main problem is that a lot of characters in PowerShell do other things in batch, and they interfere with how for loops work. Combine that with the extra of layer of string processing that goes into for /F loops, and there's a bunch of extra escaping that is needed.

Ultimately, quotes around everything and double-quoting plus escaping inner quotes seems to do the trick.

@echo off
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell -noprofile "Get-WMIObject -Query \""SELECT * from win32_logicaldisk WHERE DriveType = '3'\"" | Measure-Object -Property Size -Sum | select -ExpandProperty Sum"`) DO (
    SET var=%%F
)
echo %var%

I prefer using another way. I think it's simplier to understand and I hate cmd's for syntax

:createTempFileLoop
set "MY_TEMPFILE=%TEMP%\my~%RANDOM%~%RANDOM%~%RANDOM%~%RANDOM%~%RANDOM%.cmd"
if exist "%MY_TEMPFILE%" goto :createTempFileLoop

SET MY_SUMSIZE=-1

@REM Variant powershell.exe -Command [IO.File]::WriteAllText('%MY_TEMPFILE%', 'SET MY_SUMSIZE='+(Get-WMIObject -Query 'SELECT * from win32_logicaldisk WHERE DriveType = ''3''' ^| Measure-Object -Property Size -Sum).SUM, [System.Text.Encoding]::ASCII)

powershell.exe -Command 'SET MY_SUMSIZE='+(Get-WMIObject -Query 'SELECT * from win32_logicaldisk WHERE DriveType = ''3''' ^| Measure-Object -Property Size -Sum).SUM > %MY_TEMPFILE%

call %MY_TEMPFILE%
DEL /Q /F %MY_TEMPFILE%
echo Size is %MY_SUMSIZE%
pause
Related