在批处理脚本中获取Powershell变量值

时间:2013-12-04 05:03:07

标签: windows powershell batch-file cmd

我想在批处理脚本中获取导出的powershell变量的值。以下是示例脚本。

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

执行sample.bat时,我总是遇到错误。

.value') was unexpected at this time.

但是,如果我在powershell中执行如下操作,我可以获得正确的输出。

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

我想知道如何在批处理脚本中绕过Get-Variable命令的括号。或者想知道以任何其他方式在批处理脚本中获取导出的powershell变量的值。

2 个答案:

答案 0 :(得分:4)

如果没有更多信息我无法测试,但看看这是否有帮助:

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

答案 1 :(得分:0)

昨天从评论部分移动了答案。

我已经解决了!!我不仅要逃避右括号和半结肠。在为右括号添加转义字符后,我得到了一个不同的错误。

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

工作指令如下......

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

@foxidrive感谢您的回答,也很有效。