Home > Software design >  Is there a way to get a subtracted date from Powershell in a batch file?
Is there a way to get a subtracted date from Powershell in a batch file?

Time:06-20

I'm trying to create a .bat file get the current business day-1, so if it's Monday the date should be the Friday date(current date -3), if it's Friday the date should be Thursday date(current date -1). I can get the dates from Powershell but when i try to get the date with the subtraction it gives me this error:

get-date was unexpected at this time.

This is generated in the last part of the powershell command in bold text:

if %WEEKDAY%==3 (for /f %%i in ('powershell $dataAtual=get-date;$dataAtual=$dataAtual.AddDays(-3); **get-date** $dataAtual') do set FX=%%i) else (set FX=%CURRENTDATE%)
echo %FX%

I tried to remove the get-date so it just prints the value of $dataAtual like in powershell but it them says:

$dataAtual was unexpected at this time

Full code:

for /f %%i in ('powershell get-date -f yyy.MM.dd') do set CURRENTDATE=%%i
echo %CURRENTDATE%

for /f %%i in ('powershell get-date %CURRENTDATE% -UFormat %%u') do set WEEKDAY=%%i
echo %WEEKDAY%

if %WEEKDAY%==3 (for /f %%i in ('powershell $dataAtual=get-date;$dataAtual=$dataAtual.AddDays(-3); get-date $dataAtual') do set FX=%%i) else (set FX=%CURRENTDATE%)
echo %FX%

(I know weekday 3 is not Friday in the code above, I'm just testing for now)

CodePudding user response:

Refer to the Theo's Comment , You can write it into a batch file like this :


@echo off
set psCmd="&{$dataAtual=(Get-Date).AddDays(-1); while (1..5 -notcontains $dataAtual.DayOfWeek) { $dataAtual = $dataAtual.AddDays(-1) }; get-date $dataAtual -f yyyy.MM.dd}"
Call :RunPS %psCmd% FX
Echo %FX%
pause & Exit
::----------------------------------------------------------------------
:RunPS <PassPSCMD> <RetValue>
@for /F "usebackq tokens=*" %%i in (`Powershell %1`) do set "%2=%%i"
Goto:eof
:: End of :RunPS function
::----------------------------------------------------------------------
  • Related