Search code examples
powershellbatch-filetimestampbatch-processingtimestamp-with-timezone

Assign PowerShell command result to variable within Batch-Script


I would like to achieve what I can do in a PowerShell CLI also within a Batch-Script:

PS C:\Users\andreas.luckert> $timestamp = Get-Date -UFormat "%d-%m-%Y--%R-UTC%Z" | ForEach-Object { $_ -replace ":", "." }

PS C:\Users\andreas.luckert> echo $timestamp
26-11-2021--15.55-UTC+01

Now, within my Batch-Script, I tried approaches similar to the following

SET _timestamp=('Get-Date -UFormat "%d-%m-%Y--%R-UTC%Z" | ForEach-Object { $_ -replace ":", "." }')

Yet, it does not work.

Solutions like this look a bit hacky to me, the general instructions for batch variables does not help in this case and all of these approaches are very ugly syntax-wise in comparison to the nice and clean PowerShell command I mentioned in the very beginning. Moreover, none of them include the timezone, which is important to me.


Solution

    • You need to call powershell.exe, Windows PowerShell's CLI, in order to execute a PowerShell command from a batch file - note that such a call is expensive.

    • You need to parse the output via a for /f loop in your batch file; run for /? for help from a cmd.exe session (Command Prompt).

    • You need to double % characters that the batch file should treat verbatim.

    To put it all together:

    @echo off
    
    for /f "usebackq delims=" %%i in (`
      powershell -c "(Get-Date -UFormat '%%d-%%m-%%Y--%%R-UTC%%Z') -replace ':', '.'"
    `) do set _timestamp=%%i
    
    echo %_timestamp%
    

    Note: Consider placing -noprofile before -c to suppress loading of PowerShell's profiles, for better performance and a predictable execution environment.