Setting a variable in batch using powershell

batch-file, environment-variables, powershell, powershell-2.0

Solution

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

Problem

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

Original source

Related problems