Powershell – Get the previous day date as variable in batch file from powershell command output

batchbatch-filebatch-processingpowershellvariables

The scenario is like this. I need a previous day date (i.e. Today -1) as variable in a batch file. But if previous day is Sunday (i.e. script running on Monday) it should return the Saturday's date (i.e. Today -2). I have tried the below script but it doesnt seems to be working. Can anybody help please.

ECHO STARTING
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell -Command "& {if ^(^([Int] ^(Get-Date^).DayOfWeek^) -eq 1^) {get-date^(^(get-date^).addDays^(-2^)^) -uformat "%%d.%%m.%%Y"} Else{get-date^(^(get-date^).addDays^(-1^)^) -uformat "%%d.%%m.%%Y"} }`) DO (SET var=%%F)

ECHO DATE CAPTURED IN VARIABLE IS %var%

I have tried following command directly at command promt and it is working properly.

powershell -Command "& {if (([Int] (Get-Date).DayOfWeek) -eq 1) {get-date((get-date).addDays(-2)) -uformat "%d.%m.%Y"} Else{get-date((get-date).addDays(-1)) -uformat "%d.%m.%Y"} }

Best Answer

Save

if (((Get-Date).DayOfWeek.value__) -eq 1) {get-date((get-date).addDays(-2)) -uformat "%d.%m.%Y"} Else{get-date((get-date).addDays(-1)) -uformat "%d.%m.%Y"}

as a .ps1 file; for example C:\Batch\getvar.ps1

Then call this in your batch script with

FOR /F "tokens=* USEBACKQ" %%F IN (`powershell -ExecutionPolicy Bypass -File C:\Batch\getvar.ps1`) DO (SET var=%%F)