使用powershell批量设置变量

Kaz*_*oph 4 powershell batch-file environment-variables powershell-2.0

我一直在绞尽脑汁试图弄清楚这一点。

这段代码

@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%
Run Code Online (Sandbox Code Playgroud)

都应该返回昨天日期的响应(格式为 yyyMMdd),但是,它们没有。使用 powershell,以下代码确实有效并返回正确的响应:

$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
Run Code Online (Sandbox Code Playgroud)

但批量使用时不起作用。有什么想法吗?我试图设置该变量%Yesterday%以便稍后在脚本中使用它,但它的行为并不像我预期的那样。我确信它很简单,但我现在还不知道它是什么。

类似的问题

Hac*_*koo 5

这是您应该使用的代码来使用Powershell和设置变量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
::----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)