问题
I have been racking my brain trying to figure this out.
this code
@echo off
powershell $Yesterday = (get-date((get-date).addDays(-1)) -format yyyyMMdd)
echo %Yesterday%
::neither one of these echo anything
@echo off
powershell Set-Variable -Name "Yesterday" -Value (get-date((get-date).addDays(-1)) -format yyyyMMdd)
echo %Yesterday%
should both return a response with yesterdays date (formatted as yyyMMdd), however, they do not. Using powershell, the following code does indeed work and return the correct response:
$Yesterday = (get-date((get-date).addDays(-1)) -format yyyyMMdd)
Write-Host $Yesterday
::Both of these work in powershell
Set-Variable -Name "Yesterday" -Value (get-date((get-date).addDays(-1)) -format yyyyMMdd)
Write-Host $Yesterday
however it does not work when used in batch. Any ideas why? I am trying to set the variable %Yesterday% in order to use it later in the script, but its not behaving itself as I expected. I'm sure its something simple, but I'm not seeing what it is right now.
similar question
回答1:
This what you should use as code to set variable using Powershell and Batch
@echo off & color 0A
Title Setting a variable in batch using powershell
Set psCmd="get-date((get-date).addDays(-1)) -format yyyyMMdd"
Call :RunPS %psCmd% YesterDay
Echo YesterDay was %YesterDay%
pause & Exit
::----------------------------------------------------------------------
:RunPS <PassPSCMD> <Return value to be set as variable>
for /F "usebackq tokens=*" %%i in (`Powershell %1`) do set "%2=%%i"
Goto:eof
:: End of :RunPS function
::----------------------------------------------------------------------
回答2:
Defne the variable in batch, retrieve from Powershell
@echo off
%Yesterday% = powershell -command (get-date((get-date).addDays(-1)) -format yyyyMMdd)
echo %Yesterday%
pause
来源:https://stackoverflow.com/questions/59209855/setting-a-variable-in-batch-using-powershell