Search code examples
powershelldatetimebatch-filecmdecho

How to get output of a PowerShell command and of command ECHO in Windows batch file output on one line?


The following command line does not work in a Windows batch file:

Powershell.exe -Command Get-Date -Format 'yyyy-MM-dd HH:mm:ss' echo "Hello World"

The expected result is: 2021-05-09 12:00:00 Hello World

But PowerShell outputs the error message:

Get-Date : Cannot bind parameter 'Date'. Cannot convert value "echo" to type "System.DateTime".
Error: "The string was not recognized as a valid DateTime. There is a unknown word starting at index 0."
At line:1 char:9
+ Get-Date <<<<  -Format 'yyyy-MM-dd HH:mm:ss' echo Hello World
    + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

How to get output of the PowerShell command to get date and time in format yyyy-MM-dd HH:mm:ss and of the command ECHO in Windows batch file output on one line?


Solution

  • The command line to use in a Windows batch file is:

    @for /F "usebackq delims=" %%I in (`%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -Command Get-Date -Format 'yyyy-MM-dd HH:mm:ss'`) do @echo %%I Hello World
    

    The Windows command processor cmd.exe processing the batch file starts one more cmd.exe in background with option /c and the command line specified within set of command FOR as additional arguments. The second cmd.exe instance runs powershell.exe to get local date time and outputs it in the specified format. This output of PowerShell written to handle STDOUT (standard output) of background command process is captured by the command process which is processing the batch file and is processed after started cmd.exe terminated itself by the cmd internal command FOR.

    The output line is assigned as is to the loop variable I because of using delims= to define an empty list of string delimiters and the fact that the line does not start with a semicolon which is the default end of line character. The string value assigned to loop variable I is output with the text by the command ECHO to handle STDOUT of the command process which is processing the batch file.

    Open a command prompt, run for /? and read the output help carefully and completely from top of first to bottom of last page.

    See also the answers on: