1

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

13 Comments

This seems to just download a file called '(powershell with it's content being the command itself
Make sure to use the backtick around the command. On my keyboard, it's the key above TAB.
Yes, I am, I copied and pasted your solution.
OK, I guess it depends on what the contents of the URL are. Some characters will be interpreted differently in Batch, especially <, |, >,&. Also, SET has a limitation in that it only works for one line of text. If that's an issue, maybe you should pipe the output to a temporary file instead? Can you clarify what the contents of the URL are?
You must have run it in the cmd window directly. Use %a in cmd, but %%a in a batch file. Don't forget to change both places.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.