简体   繁体   中英

Is there a way to get a subtracted date from Powershell in a batch file?

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)

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
::----------------------------------------------------------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM