Shell – Return PowerShell Command result in batch file

batchpowershell

I have a powershell command that works pretty well in returning the date i want in the format I need. I have been unable to call this command in a batch file to be used in a separate script.

C:\Users\xxx>powershell -command (get-date((get-date).addDays(-1)) -uformat "
%Y%m%d")
20171115

This appears to work although the date format isnt what I would like for it to be:

set "psCommand=powershell -command "(get-date((get-date).addDays(-1)))""
for /f "delims=" %%I in ('%psCommand%') do set "leaf=%%I"
echo %leaf% >> uploadsp.txt

Output is: Wednesday, November 15, 2017 5:19:34 PM

Thanks

So I may have gotten ahead oh myself. This is what I had previously and I was merely trying to change it to get date-1.

echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit

Best Answer

I was able to get this to work as expected as you describe by piping the PowerShell script logic within the batch script to a temp PS1 file, and then using a FOR /F loop to take the result of the executed PowerShell script to subtract the number of days from the current date within it, and save that result as a variable to use in the batch script for your needs (%leaf%) afterwards.

Please note I had to double up the percent signs in the PowerShell -format "%%Y%%m%%d" to ensure those symbols are used as literal characters and not special characters by the batch script.

Escaping Percents

The % character has a special meaning for command line parameters and FOR parameters.

To treat a percent as a regular character, double it:

%%

Escape Characters, Delimiters and Quotes


Batch Script

@ECHO ON

:DynamicPSScriptBuild
SET PSScript=%temp%\~tmp%~n0.ps1
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
ECHO get-date((get-date).addDays(-1)) -uformat "%%Y%%m%%d">>"%PSScript%"

FOR /F "DELIMS=" %%I IN ('Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%'"') DO SET "leaf=%%I"
echo %leaf% >> uploadsp.txt
EXIT

Further Resources

Related Question