[英]How to use a PowerShell function return as a variable in a batch file
我试图使用 myPowershellScript.ps1 的返回作为我的批处理文件中的变量。
我的PowershellScript.ps1
function GetLatestText
{
return "Hello World"
}
我正在尝试使用 For /F function。可能有更好的方法。
myBatch.bat
for /f "delims=" %%a in (' powershell -command "\\Rossi2\Shared\myPowershellScript.ps1" ') do set "var=%%a"
echo %var%
所需的 output,将在 cmd window 中包含“Hello World”output。
我试图使用批处理文件,因为一些旧进程使用它们。 对于较新的流程,我在 PowerShell 中执行了所有操作,并且工作正常。
当前output为空白。
您尝试从批处理文件的 PowerShell 脚本中捕获 output 的语法是正确的(假设脚本中的单行output), [1]除了使用-File
的powershell.exe
参数更可靠, Windows PowerShell CLI 比-Command
参数。
-File
与-Command
的信息,请参阅此答案。您的问题出在 PowerShell 脚本本身:
您正在定义function Get-LatestText
,但您没有调用它,因此您的脚本不会生成 output。
存在三种可能的解决方案:
在 function 定义之后显式调用Get-LatestText
; 如果要传递脚本接收到的任何 arguments,请使用Get-LatestText @args
根本不要定义 function,将 function 主体作为脚本主体。
如果您的脚本包含多个函数,并且您想有选择地调用其中一个函数:在您的 PowerShell CLI 调用中, 点源脚本文件 ( . <script>
),然后调用 function (这确实需要-Command
):
for /f "delims=" %%a in (' powershell -Command ". \"\\Rossi2\Shared\myPowershellScript.ps1\"; Get-LatestText" ') do set "var=%%a" echo %var%
[1] for /f
逐行循环命令的 output(忽略空行),因此对于多行 output,只有最后一行将存储在%var%
中 - 需要更多努力来处理多行 output。
您可以将批处理和 powershell 组合在单个文件中(将其另存为.bat
):
<# : batch portion
@echo off & setlocal
for /f "tokens=*" %%a in ('powershell -noprofile "iex (${%~f0} | out-string)"') do set "result=%%a"
echo PS RESULT: %result%
endlocal
goto :EOF
: end batch / begin powershell #>
function GetLatestText
{
return "Hello World"
}
write-host GetLatestText
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.