Windows – Trouble using powershell output as a variable in batch file

batchcommandpowershellpromptwindows

I can manually run this command from a Windows Command Prompt:

powershell (new-timespan -start 01/01/2000 -end (get-date)).days % 14

And it returns a number from 0 to 13. I want to use this result in a batch file, but this line gives an error back:

for /f %%i in ('powershell (new-timespan -start 01/01/2000 -end (get-date)).days % 14') do set doc=%%i

The error:

).days was unexpected at this time.

I suspect I need to add more quotes, double quotes, apostrophes and brackets but I've tried every possible combination and can't get it to work. I think maybe some ^^s are needed too?

Best Answer

In the FOR command you need escape not only the parenthesis, but the mod (percent) as well. The parens are escaped with ^, the percent by %. Note that this will only work within a batch file, not the command line.

FOR /F %%i IN ('powershell ^(new-timespan -start 01/01/2000 -end ^(get-date^)^).days %% 14') DO (
    SET doc=%%i
)

ECHO %doc%