Getting Powershell variable value in batch script

2019-05-10 22:02发布

问题:

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.

回答1:

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


回答2:

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.