如何将单个 PowerShell 输出字符串放入 cmd 变量?

Air*_*Nut 3 powershell cmd batch-file

我有一个输出单个字符串值的 PowerShell 脚本。我有一个 cmd 批处理脚本,需要执行 PowerShell 脚本并将单个 PowerShell 输出值放入批处理脚本中的变量中。我正在寻找各种导出到文件或读取文件的方法,但这不是我想要的。谢谢!

(编辑)这是我尝试使用它的地方(响应发布脚本):

@echo off
REM The next line puts the .ps1 output into the variable
REM and, obviously, this does not work
set pass_word=<C:\temp\PullPassword.ps1
tabcmd login -s "http://myserver.net" -u mylogon -p %pass_word%
Run Code Online (Sandbox Code Playgroud)

(编辑)我在这里看到了OP的答案Getting Powershell variable value in batch script,还查看了foxdrive的答案,所以我开始使用FOR...DO语句。我认为我对 cmd 非常擅长,但不明白为什么我的命令不起作用:

for /f "delims=" %%a in ('powershell . "C:\temp\PullPassword.ps1"') do set val=%%a
echo  %a% 
Run Code Online (Sandbox Code Playgroud)

当我在另一篇文章中查看 Foxdrive 的完整答案时,我震惊了:%a% 是错误的,我需要 %val%!噢,耻辱!以下作品:

@echo off
set mypath=C:\temp\PullPassword.ps1
for /f "delims=" %%a in ('powershell . "C:\temp\PullPassword.ps1"') do set pass_word=%%a 
tabcmd login -s "http://myserver.net" -u mylogon -p %pass_word%
Run Code Online (Sandbox Code Playgroud)

因此,我会记下它的到期时间,并将 Foxdrive 的答案标记为正确,即使是另一篇文章澄清了我的错误。

fox*_*ive 6

这可能会有所帮助:它期望 powershell 脚本将文本输出到 STDOUT,这是它出现的正常位置。

@echo off
for /f "delims=" %%a in (' powershell "script.ps1" ') do set "var=%%a"
Run Code Online (Sandbox Code Playgroud)