How can you set a PowerShell output as a batch variable? [duplicate] - powershell

This question already has answers here:
How to set commands output as a variable in a batch file [duplicate]
(9 answers)
Closed 2 years ago.
I created a batch file that executes a PowerShell command. This should read out the capacity of the notebook battery. How can the result of the command be defined as a variable?
Something with tokens is needed for that, right? Can someone help me? In the end, CMDs/Natchs "echo" should output the result.
powershell -Executionpolicy Bypass -Command "(Get-WmiObject -Class "BatteryFullChargedCapacity" -Namespace "ROOT\WMI").FullChargedCapacity"

Try this:
for /f "tokens=* delims= " %%a in ('powershell -Executionpolicy Bypass -Command "(Get-WmiObject -Class "BatteryFullChargedCapacity" -Namespace "ROOT\WMI").FullChargedCapacity"') do set "var=%%a"
You can replace var with variable name.

You can try like this batch code using for in do loop : for /f
#echo off
Set PS_CMD=Powershell ^
"(Get-WmiObject -Class "BatteryFullChargedCapacity" -Namespace "ROOT\WMI"^).FullChargedCapacity"
#for /f "tokens=* delims=" %%a in ('%PS_CMD%') do set "var=%%a"
echo %Var%
pause

Related

I'm trying to return the AppPool status within a batch script using Powershell

I'm trying something like this
for /f "usebackq delims=" %%a in ('
Powershell.exe -ExecutionPolicy Bypass -Command Invoke-Command -ComputerName <AServerNAme> -ScriptBlock { Get-WebAppPoolState AppPoolName }
') do set "value=%%a"
echo What is %value%
I want the value to contain stopping, stopped, starting...etc, but all I can get back is null
Thanks In Advance
Aside from your incorrect use of the 'USEBACKQuotes' option in your For loop, (because you weren't using them), you also need to define your value variable using the string value of the object's property, not the object itself.
I would therefore advise that you use something more like this:
Set "value="
For /F Delims^=^ EOL^= %%G In ('
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -Command
"Invoke-Command -ScriptBlock {(Get-WebAppPoolState AppPoolName).Value}"
2^>NUL') Do Set "value=%%G"
If Defined value Echo What is %value%
You will also note that I have removed the -ExecutionPolicy option, because that is usually used for running PowerShell scripts (-File), not for commands (-Command).

PowerShell mask Get-ItemPropertyValue one-liner in batch file

I use PowerShell one-liners in several batch scripts, but seem failing to escape the following one correctly:
if not defined LANGUAGE (
for /f "usebackq" %%v in (`PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "(Get-ItemPropertyValue -Path 'HKCU:Control Panel\International\' -Name 'LocaleName').Split('-')[0]"`) do set LANGUAGE=%%v
)
I verified that it is this line that fails in my batch file. The idea behind the code is to read the value from the registry and assign the first part before the hyphen to an environment variable. So if the registry value is "de-DE", LANGUAGE shall have the value of "de".
I cannot reproduce an issue with the code you've provided.
I would however suggest you consider other approaches - compare these examples and note which executes the fastest
#Echo off
Setlocal
For /f "delims=" %%v in ('where /r "%Windir%\SysWOW64\WindowsPowerShell" powershell.exe')Do Set "powershell=%%v -nologo -noprofile"
Echo(%TIME%
For /f "usebackq" %%v in (`PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "(Get-ItemPropertyValue -Path 'HKCU:Control Panel\International\' -Name 'LocaleName').Split('-')[0]"`) do set "LANGUAGE=%%v"
Set LANG
Echo(%TIME%
For /f "usebackq tokens=1 Delims=-" %%G in (`
%powershell% -c "Get-ItemPropertyValue -Path 'HKCU:Control Panel\International\' -Name 'LocaleName'"
`)Do Set "LANGUAGE=%%G"
Set LANG
Echo(%TIME%
For /f "Skip=1 tokens=3 Delims=- " %%G in ('reg query "HKEY_CURRENT_USER\Control Panel\International" /v localename')Do Set "LANGUAGE=%%G"
Set LANG
Echo(%TIME%
Endlocal
Goto:Eof

is there a way to make batch code more compact?

I am trying to create a 1 line code which downloads files and executes them. I have tried the & and && method to run more commands one after another. but I am having a hard time trying to put the second line with the first one using &.
powershell -Command "Invoke-WebRequest https://github.com/-----/unixC/archive/main.zip -OutFile I.zip" & powershell Expand-Archive I.zip & for /f %%a IN ('dir "I\unixC-main" /b') do move "I\unixC-main\%%a" "%cd%\"
#RD /S /Q "I" & del /q /f I.zip log.txt README.md & start unixC.bat & start /b "" cmd /c del "%~f0"&exit /b
Is there any way to make this snippet of code even shorter? and more compact?
Rasil
Like others have said, the whole thing could be done in powershell. Semicolon seperates commands. -command is the default so you can leave it out. Wget is a powershell alias for invoke-webrequest.
powershell wget https://github.com/-----/unixC/archive/main.zip -OutFile I.zip; Expand-Archive I.zip
Example powershell replacement for the whole thing:
Invoke-WebRequest https://github.com/-----/unixC/archive/main.zip -OutFile I.zip
Expand-Archive I.zip
move-item i\unixC-main\* $pwd # $pwd is optional
remove-item -recurse i
remove-item -force i.zip,log.txt,readme.md
.\unixC.bat
remove-item $args[0]
Try parenthesising for /f %%a IN ('dir "I\unixC-main" /b') do move "I\unixC-main\%%a" "%cd%\" and then append the &{second line}

Trouble setting Batch variable to output of command

I have the following line in a .BAT file attempt to get a UTC string.
FOR /F "tokens=*" %g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %Y-%m-%dT%H_%M_%SZ"') do (SET VAR=%g)
Which makes use of this PowerShell line which works from command prompt.
powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %Y-%m-%dT%H_%M_%SZ"
And I get the error.
Y-dTM_g) was unexpected at this time.
This is part of a wider batch file so I can't just do it directly in a PowerShell script.
I took my initial inspiration from here.
How to set commands output as a variable in a batch file
Update:
Tried this code to no avail.
test.bat
FOR /F "tokens=*" %%g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %Y-%m-%dT%H_%M_%SZ"') do (
SET "VAR=%%g"
)
echo %VAR%
Getting the output.
D:\foo>FOR /F "tokens=*" %g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat m-H_SZ"') do (SET "VAR=%g" )
D:\foo>(SET "VAR=m-H_SZ" )
D:\foo>echo m-H_SZ
m-H_SZ
D:\foo>
Using code inside of a batch consumes the first % so you need to double up on it. Simply try this:
FOR /F "tokens=*" %%g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %%Y-%%m-%%dT%%H_%%M_%%SZ"') do SET "VAR=%%g"
It is also good to always enclose your set variables in double quotes to eliminate any possible whitespace.
The original code will only work when running it from cmd terminal.
If you set variables inside a loop you however need delayedexpansion:
#echo off
setlocal enabledelayedexpansion
FOR /F "tokens=*" %%g IN ('powershell -command "Get-Date -date (Get-Date).ToUniversalTime()-uformat %%Y-%%m-%%dT%%H_%%M_%%SZ"') do (
SET "VAR=%%g"
)
echo !VAR!
for more on delayed expansion, see from cmd.exe:
set /?
setlocal /?

How to store response of url in a variable batch scripting

I am trying to store the response of a URL into a variable in a batch script
Example:
set initial=PowerShell -Command "(new-object net.webclient).DownloadString('https://some-url/id')"
I'm trying to store the response of:
PowerShell -Command "(new-object net.webclient).DownloadString('https://some-url/id')"
into variable:
initial
But this is not working. How can I accomplish my goal?
Use for /f. Something like this.
for /f "usebackq delims=" %%a in (`PowerShell -Command "(new-object net.webclient).DownloadString('https://some-url/id')"`) do set initial=%%a
This an example showing you how to get your public ip address :
#echo off
set "URL=http://myexternalip.com/raw"
Call :GetResponse %URL%
echo %initial%
Pause>nul & exit
::*****************************************************************
:GetResponse <URL>
for /f "usebackq delims=" %%a in (`PowerShell -Command "(new-object net.webclient).DownloadString('%1')"`) do set "initial=%%a"
Exit /b
::*****************************************************************