Setting a variable in batch using powershell

こ雲淡風輕ζ 提交于 2019-12-21 19:49:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!