How to store response of url in a variable batch scripting - powershell

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

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

Batch file to be converted in powershell script

I am new on powershell, I want to convert the following batch script into powershell. The reason why I want this conversion is because this script will be run on a server from my task scheduler and due to the fact that the cmd is not working with UNC paths I think that could be a good workaround.
This script is checking if there are 20 zip files in a folder and in case they are found then starts a python script to unzip them (mandatory)
for /f %%a in ('dir /b W:\XXX\XXX\*.zip ^| find /c /v ""') do (
if /i %%a EQU 0 EXIT
if /i %%a NEQ 20 timeout /t 300 /nobreak
if /i %%a NEQ 20 Powershell.exe -executionpolicy remotesigned -File W:\XXX\XXX\powershellerrormail.ps1
if /i %%a NEQ 20 EXIT
if /i %%a EQU 20 (python W:\XXX\XXX\SSC_Unzipping.py)
pause)
EXIT

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 /?

Variable was unexpected this time

I am trying to run this command in command-line:
for /f %fpath in ('dir %1 /s /b /a-d /o:gn') do echo %fpath
And I get an error:
%fpath was unexpected at this time.
What is wrong in my command?
Found the problem.
For variable must to be one-letter variable.
This code works:
for /f %P in ('dir %1 /s /b /a-d /o:gn') do echo %P