1

I have the following line in a .BAT file attempt to get a UTC string.

FOR /F "tokens=*" %g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %Y-%m-%dT%H_%M_%SZ"') do (SET VAR=%g)

Which makes use of this PowerShell line which works from command prompt.

powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %Y-%m-%dT%H_%M_%SZ"

And I get the error.

Y-dTM_g) was unexpected at this time.

This is part of a wider batch file so I can't just do it directly in a PowerShell script.

I took my initial inspiration from here.

How to set commands output as a variable in a batch file

Update:

Tried this code to no avail.

test.bat

FOR /F "tokens=*" %%g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %Y-%m-%dT%H_%M_%SZ"') do (
    SET "VAR=%%g"
)

echo %VAR%

Getting the output.

D:\foo>FOR /F "tokens=*" %g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat m-H_SZ"') do (SET "VAR=%g" )

D:\foo>(SET "VAR=m-H_SZ" )

D:\foo>echo m-H_SZ
m-H_SZ

D:\foo>
Geesh_SO
  • 2,156
  • 5
  • 31
  • 58

1 Answers1

3

Using code inside of a batch consumes the first % so you need to double up on it. Simply try this:

FOR /F "tokens=*" %%g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %%Y-%%m-%%dT%%H_%%M_%%SZ"') do SET "VAR=%%g"

It is also good to always enclose your set variables in double quotes to eliminate any possible whitespace.

The original code will only work when running it from cmd terminal.

If you set variables inside a loop you however need delayedexpansion:

@echo off
setlocal enabledelayedexpansion
FOR /F "tokens=*" %%g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %%Y-%%m-%%dT%%H_%%M_%%SZ"') do (
    SET "VAR=%%g"
)
echo !VAR!

for more on delayed expansion, see from cmd.exe:

set /?
setlocal /?
Gerhard
  • 22,678
  • 7
  • 27
  • 43