Home > Blockchain >  right notation in batchscript while using powershell command
right notation in batchscript while using powershell command

Time:02-27

I dont know, what is wrong, but it outputs only "powershell" :D I think i did something wrong with the " and ' notations... Tried some combinations, but it won´t work.

for /f %%a in ("powershell -c [math]::Round((Get-ChildItem 'C:\Program Files (x86)\Steam\' -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)") do set "test=%%~a"
echo %test%

output:

powershell

CodePudding user response:

Here's a quick example to assist you:

@For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
 -NoLogo -NoProfile -Command
 "[Math]::Round( ( ( Get-ChildItem 'C:\Program Files (x86)\Steam' -Recurse | "^
 "Measure-Object -Property Length -Sum -ErrorAction Stop ).Sum / 1MB ), 2 )"
 ') Do @Set "test=%%G"
@Set test 2>NUL

Please note, that as you ware using Round, I specifically asked for it to two decimal places.

If you do not need to round, but just need two decimal places, then you could change it to this:

@For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
 -NoLogo -NoProfile -Command
 "\"{0:N2}\" -F ( ( Get-ChildItem 'C:\Program Files (x86)\Steam' -Recurse | "^
 "Measure-Object -Property Length -Sum -ErrorAction Stop ).Sum / 1MB )"
 ') Do @Set "test=%%G"
@Set test 2>NUL

CodePudding user response:

In addition of Compo's Answer, you can do something like this in batch using Powershell :

@echo off
Title Get Folder Size MB
Set Folder=C:\Program Files (x86)\Steam\
Call :Get_Size "%Folder%"
echo "%Folder%" ==^> Size=%Size%
Pause & Exit /B
::----------------------------------------------------------------------------------------------------------------------------------
:Get_Size <Folder> <Size>
set psCommand=Powershell -C "((Get-ChildItem ""%~1"" -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB).ToString('N2')"
@for /f "delims=" %%S in ('%psCommand%') do set Size=%%S MB
Exit /B
::----------------------------------------------------------------------------------------------------------------------------------
  • Related