4

I want get value of an exported powershell variable in a batch script. Below are the sample scripts.

sample.ps1

$myname="user1"

sample.bat

@echo on
FOR /F "delims=" %%i IN ('powershell . "D:\sample.ps1"; (Get-Variable myname).value') DO SET VAL=%%i
echo %VAL%
pause

While executing sample.bat, I am always getting below error.

.value') was unexpected at this time.

But, if I execute like below in powershell I am able to get proper output.

. "D:\sample.ps1"; (Get-Variable myname).value

I want to know how to escape the parenthesis around Get-Variable command in batch script. Or would like to know any other way to get the value of exported powershell variable in batch script.

9
  • See if this post is what you are after. stackoverflow.com/questions/3414300/… Commented Dec 4, 2013 at 5:10
  • @malexander Thank you for the link. But in this they are getting output of a powershell command say get-date and reading the value in batch script. Commented Dec 4, 2013 at 5:27
  • Also, tried to escape the closing parenthesis as below but still getting error. FOR /F "delims=" %%i IN ('powershell . "D:\sample.ps1"; (Get-Variable myname^).value') DO SET VAL=%%i echo %VAL% Commented Dec 4, 2013 at 5:31
  • Correct me if I'm wrong, but doesn't BAT script recognize \ as an escape character? Commented Dec 4, 2013 at 5:56
  • @Vish According to my understanding \ will be used as escape character for regex patterns only. Please check here Commented Dec 4, 2013 at 6:05

2 Answers 2

8

I can't test this without more information, but see if this helps:

@echo on
FOR /F "delims=" %%i IN ('"powershell . "D:\sample.ps1"; (Get-Variable myname).value"') DO SET VAL=%%i
echo %VAL%
pause
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @foxidrive, can u let me know if we can handle multiple values returned/exported from a powershell and save it in multiple variables in a batch file
0

Moved the answer added yesterday from comments section.

I have solved it!! I have to escape not only closing parenthesis and also the semi colon. I got a different error after adding escape character for closing parenthesis.

SET VAL=Get-Variable : Cannot find a variable with name 'myname'. 

Working command is as follows...

FOR /F "delims=" %%i IN ('powershell . "D:\sample.ps1"^; (Get-Variable myname^).value') DO SET VAL=%%i

@foxidrive Thank you for your answer and it also worked.

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.