Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a variable in batch using powershell

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

like image 582
Kazankoph Avatar asked Oct 15 '25 14:10

Kazankoph


1 Answers

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
::----------------------------------------------------------------------
like image 109
Hackoo Avatar answered Oct 18 '25 04:10

Hackoo