Setting a variable in batch using powershell - 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

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

Here is a one liner that will provide a var for yesterday's date in your batch script. The second line cleans up the temp file used to create the variable.
powershell -command "((Get-date).AddDays(-1)).ToString('yyyyMMdd')">captureVar && set /p Yesterday=<captureVar
if exist captureVar del captureVar
Line 1 starts out by instructing the cmd line to use PowerShell for the commands contained within the double quotes.
powershell -command "the powershell command(s)"
As it's name implies, the first PowerShell cmdlet will perform a function to Get-Date. Then, AddDays is used to change the date from the current value. A negative number will subtract and a positive number will add.
The default format looks like Friday, December 20, 2019 6:18:29 PM
To change the format, you must change the date into a string with format instructions
.ToString('dddd MM/dd/yyyy HH:mm:ss.ffff K')
The output of the PowerShell command is redirected into a file named captureVar. Another option would have been to have PowerShell write it to a file.
powershell -command "((Get-date).AddDays(-1)).ToString('yyyyMMdd') | set-content 'captureVar'" && set /p Today=<captureVar
I used && to make it a one liner. But you can set the var anytime after value has been written to the file.
set /p Today=<captureVar
The next line cleans up the temp file used to help create the var.

Defne the variable in batch, retrieve from Powershell
#echo off
%Yesterday% = powershell -command (get-date((get-date).addDays(-1)) -format yyyyMMdd)
echo %Yesterday%
pause

Related

How to get output of a PowerShell command and of command ECHO in Windows batch file output on one line?

The following command line does not work in a Windows batch file:
Powershell.exe -Command Get-Date -Format 'yyyy-MM-dd HH:mm:ss' echo "Hello World"
The expected result is: 2021-05-09 12:00:00 Hello World
But PowerShell outputs the error message:
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "echo" to type "System.DateTime".
Error: "The string was not recognized as a valid DateTime. There is a unknown word starting at index 0."
At line:1 char:9
+ Get-Date <<<< -Format 'yyyy-MM-dd HH:mm:ss' echo Hello World
+ CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand
How to get output of the PowerShell command to get date and time in format yyyy-MM-dd HH:mm:ss and of the command ECHO in Windows batch file output on one line?
The command line to use in a Windows batch file is:
#for /F "usebackq delims=" %%I in (`%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -Command Get-Date -Format 'yyyy-MM-dd HH:mm:ss'`) do #echo %%I Hello World
The Windows command processor cmd.exe processing the batch file starts one more cmd.exe in background with option /c and the command line specified within set of command FOR as additional arguments. The second cmd.exe instance runs powershell.exe to get local date time and outputs it in the specified format. This output of PowerShell written to handle STDOUT (standard output) of background command process is captured by the command process which is processing the batch file and is processed after started cmd.exe terminated itself by the cmd internal command FOR.
The output line is assigned as is to the loop variable I because of using delims= to define an empty list of string delimiters and the fact that the line does not start with a semicolon which is the default end of line character. The string value assigned to loop variable I is output with the text by the command ECHO to handle STDOUT of the command process which is processing the batch file.
Open a command prompt, run for /? and read the output help carefully and completely from top of first to bottom of last page.
See also the answers on:
Time is set incorrectly after midnight
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
You could of course just do it like this:
PowerShell Write-Host (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') Hello World
Although, as this is from a pre-written batch-file, I'd advise that you use full paths and more readable and understandable syntax:
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -Command "Write-Host (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') Hello World"

How to pass batch file variables to PowerShell script? [duplicate]

This question already has an answer here:
Displaying SET variable
(1 answer)
Closed 3 years ago.
I am attempting to pass a number of variables processed by my batch file to a Powershell script. The problem I face is that firstly the entire results from the batch file come up in command prompt and next to the variables I intend to pass are not passed to the Powershell Script. Additionally, the variable I have to output the contents of the log file in just send the command back to the screen.
I have tried the following links and these links got me as far as I am now:
Batch file to execute a Powershell script
Pass variable from batch to powershell
Pass parameter from a batch file to a PowerShell script
Pass batch variables with spaces in them to powershell script?
Batch File side
set LOG_FILE = "GDGAGnklasj;oks;fk;dkf lkl;"
set oName = Name
set oStart = "%YYYY%%MM%%DD% %TIME%"
set oStatus = 0
set oEnd = "%YYYY%%MM%%DD% %TIME%"
set oDateRan = %YYYY%%MM%%DD%
set oLog =for /f "delims=" %%i in (%LOG_FILE%) do set content=%content% %%i
echo Updating Database >> %LOG_FILE% 2>&1
cmd /S powershell.exe -ExecutionPolicy Bypass -File "C:\Reporting\updateTool.ps1" "%oName%" "%DateRan%" "%oStart%" "%oEnd%" "%oStatus "%oLog%
PowerShell Script
param (
[string]$oName
)
"This is $oName"
My intent is to set the variables within the batch file then send them to Powershell for processing.
Be very careful of spaces.
set oName=taco
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '.\ScriptName.ps1' -oName '%oName%' "
Oh Easy-Peasy, I do this for my Power shells that we need CMD wrappers for quite a bit.
I have to run to the train so this is going to be a bit meh at the moment I will firm it up in a bit, right now just going to paste in some example code so I can make it your code
Okay, what, umm, what did you intend for this Particular code to.l do ? I can't seem to figure out what you were intending with this, is it just some dummy code?
set oLog =for /f "delims=" %%i in (%LOG_FILE%) do set content=%content% %%i
echo Updating Database >> %LOG_FILE% 2>&1
Okay on further review I think you want to read the log into a couple of sttring variables in CMD, then use one of them in your call of the script..... but, why?
The strings will append to each other and you will be limited to 8191 characters max, and PowerShell can easily read the content of the log file because you pass the name to Powershell.
That seems like a better plan, no?
All your code where you have YYYY MM DD those are variables you will need to define before using, not sure if that is understood if so all good.
.CMD Script:
#(
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO OFF
SET "_PSScript=C:\Reporting\UpdateTool.ps1"
REM SET "_DebugPreference=Continue"
SET "_DebugPreference="SilentlyContinue"
SET "_LOG_FILE=GDGAGnklasj;oks;fk;dkf lkl;"
SET "_oName=Name."
SET "_oStart=%YYYY%%MM%%DD% %TIME: =0%"
SET /a "_Status=0"
SET "_oEnd=%YYYY%%MM%%DD% %TIME: =0%"
SET "_oDateRan=%YYYY%%MM%%DD%"
)
SET "_PSCMD=Powershell "%_PSScript%" -DebugPreference "%_DebugPreference%" -LOG_FILE "%_LOG_FILE%" -oName "%_oName%" -oStart "%_oStart%" -Status %_Status% -oEnd "%_oEnd%" -oDateRan "%_oDateRan%" "
%_PSCMD% 2>&1 >> "_LOG_FILE"
PS1:
## Script: UpdateTool.ps1
#
param(
[String]$LOG_FILE = 'c:\admin\default.log',
[String]$oName = 'default name'
[String]$oStart = $(Get-date -F "yyyyMMdd HH:mm:ss.ms"),
[Int]$oStatus = 0,
[String]$oEnd = $(Get-date -F "yyyyMMdd HH:mm:ss.ms"),
[String]$oDateRan = $(Get-date -F "yyyyMMdd"),
$DebugPreference = "SilentlyContinue"
)

How to replace the given line of text file in looping structure using windows batch file

set instance=3
for /L %%A in (1,1,%instance%) do (
set /p var=LogfileName: trial.txt
set rep=LogfileName: logfile.txt
echo %var%
powershell -Command "(gc InputFile.txt) -replace '%var%', '%rep%' | Out-File InputFile.txt"
)
I am not able to replace the line in text file using this commands. And also I am not getting how to take the line number and store the string in that particular lile in file into a batch file variable.
% variables in batch files are expanded at parse time (when the statement is read). Since the entire for statement, including the action block, is read as one statement, %var% and %rep% are expanded before the loop is executed, meaning they evaluate to empty strings.
To have the variables inside the loop expanded at execution time you need to enable delayed expansion and use ! notation:
setlocal EnableDelayedExpansion
set instance=3
for /L %%A in (1,1,%instance%) do (
set /p var=LogfileName: trial.txt
set rep=LogfileName: logfile.txt
echo !var!
powershell -Command "(gc InputFile.txt) -replace '!var!', '!rep!' | Out-File InputFile.txt"
)
For further explanation see Raymond Chen's blog.

Order of precedence with batch and Powershell statements

PowerShell $date = Get-Date; $date=$date.AddDays(%%I); $date.ToString('MM-dd-yyyy') >c:\temp\datas
I would like to run the above command in the following order
1- Replace the %%I with the current value, lets say -1
2- Run the powershell command as follow
PowerShell $date = Get-Date; $date=$date.AddDays(-1); $date.ToString('MM-dd-yyyy')
3- Put the result the the file C:\temp\datas
Can it be done?
Why haven't you simply tried that? It works fine, although it is quite slow. I assume you really want to use append mode, otherwise your file never gets more than one row.
#echo off
for /l %%I in (-10, 1, 10) do PowerShell $date = Get-Date; $date=$date.AddDays(%%I); $date.ToString('MM-dd-yyyy') >>c:\temp\datas
The following more complicated form also works. I'm not sure when this form is needed
#echo off
for /l %%I in (-10, 1, 10) do PowerShell -command "&{$date = Get-Date; $date=$date.AddDays(%%I); $date.ToString('MM-dd-yyyy')}" >>c:\temp\datas
Calling PowerShell for each iteration is very slow because it takes time for PowerShell to load each time. It would be much faster if you put the loop within PowerShell.
Another option that would work more efficiently with a batch loop is to use my GetTimestamp.bat hybrid JScript/batch utility:
#echo off
for /l %%I in (-10, 1, 10) do call getTimestamp -od %%I -f "{mm}-{dd}-{yyyy}" >>c:\temp\datas

Batch file assign returned values from a command into a variable (from powershell)

i am refering to this question
ASSIGN win XP commandline output to variable
i am trying to use it on a powershell code segment
so i typed
powershell date (get-date).AddDays(-1) -format yyyyMMdd
and confirm it returns like
20100601
but then if i tried to
for /f "tokens=*" %a in ('powershell date get-date -format yyyyMMdd
') do set var=%a
then it failed to work as expected. how can i transfer the date to a variable?
Maybe
for /f "tokens=*" %a in ('powershell "get-date; get-date -format yyyyMMdd"') do set var=%a
is what you wanted.