首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从powershell中获取返回的值并在批处理文件中获得?

如何从powershell中获取返回的值并在批处理文件中获得?
EN

Stack Overflow用户
提问于 2015-12-24 10:37:23
回答 5查看 29K关注 0票数 8

我正在尝试使用命令执行批处理文件中的powershell : Powershell .\nameoffile.ps1

PowerShell返回一些值1、4、0和-1。如何从批处理中获得这些值?当我使用%errorlevel%时,它只返回0(这意味着脚本没有问题)。我也尝试过在PowerShell中使用Exit命令(Exit 4),但它不起作用。你能帮帮我吗?

编辑我找到了一个解决方案,如果有人感兴趣。

powershell "&{.\test.ps1 %* ;exit $LastExitCode}" set code=%errorlevel%

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-01-20 14:07:35

代码语言:javascript
运行
复制
powershell "&{.\test.ps1 %* ;exit $LastExitCode}" set code=%errorlevel%
票数 6
EN

Stack Overflow用户

发布于 2015-12-24 17:10:50

如果需要在bat环境中使用此值,请使用FOR /F

代码语言:javascript
运行
复制
@echo off
for /f "delims=" %%a in ('powershell .\test.ps1') do Set "$Value=%%a"

Echo Value received from Powershell : %$Value%
票数 17
EN

Stack Overflow用户

发布于 2017-04-26 22:43:45

我知道现在回答这个问题有点晚了,但我想尝试一下,以防有人需要更详细的解决方案。所以,它开始了。

我创建了一个批处理函数,它将为您执行ps脚本并返回一个值,如下所示:

代码语言:javascript
运行
复制
:: A function that would execute powershell script and return a value from it.
:: <PassPSCMD> pass the powreshell command, notice that you need to add any returning value witth Write-Host
:: <RetValue> the returned value
:RunPS <PassPSCMD> <RetValue>
  for /F "usebackq tokens=1" %%i in (`Powershell %1`) do set returnValue=%%i
  set "%2=%returnValue%"
Goto:eof
:: End of :RunPS function

现在,作为使用它的一个例子:

代码语言:javascript
运行
复制
set psCmd="&{ Write-Host 'You got it';}"
call :RunPS %psCmd% RetValue
echo %RetValue%

这将显示在控制台屏幕上

作为一个更复杂的例子,我要补充如下:

让我们假设我们想要检查VM是打开还是关闭,这意味着它是打开还是关闭,所以我们可以这样做:

代码语言:javascript
运行
复制
 :CheckMachineUpOrDown <returnResult> <passedMachineName>
   set userName=vCenterAdministratorAccount
   set passWord=vCenterAdminPW
   set vCenterName=vcenter.somedmain.whatever
   set psCmd="&{Add-PSSnapin VMware.VimAutomation.Core; Connect-VIServer -server %%vCenterName%% -User %userName% -Password %passWord%; $vmServer = Get-VM %2;Write-Host ($vmServer.PowerState -eq 'PoweredOn')}"

   call :RunPS %psCmd% RetValue
   if "%RetValue%" EQU "True" (set "%1=Up") else (set "%1=Down")
 Goto:eof

:: A function that would execute powershell script and return a value from it.
:: <PassPSCMD> pass the powreshell command, notice that you need to add any returning value witth Write-Host
:: <RetValue> the returned value
:RunPS <PassPSCMD> <RetValue>
  for /F "usebackq tokens=1" %%i in (`Powershell %1`) do set returnValue=%%i
  set "%2=%returnValue%"
  Goto:eof
:: End of :RunPS function

现在,如何使用:CheckMachineUpOrDown函数?

只需遵循以下示例:

代码语言:javascript
运行
复制
set Workstation=MyVMName
call :CheckMachineUpOrDown VMStatus %Workstation%
echo %VMStatus%

这将显示,如果VM是启动或下降,如果机器是关闭的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34451444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档