我知道现在回答这个问题有点晚了,但我想试一试,以防万一有人需要更详细的解决方案。所以,就这样吧。
我创建了一个批处理函数,它会为您执行 ps 脚本并返回一个值,如下所示:
:: 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
现在,作为一个使用它的例子:
set psCmd="&{ Write-Host 'You got it';}"
call :RunPS %psCmd% RetValue
echo %RetValue%
这将显示在控制台屏幕上你知道了
作为一个更复杂的例子,我会补充:
假设我们要检查 VM 是 Up 还是 Down,这意味着它是打开还是关闭,所以我们可以执行以下操作:
: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 函数?
只要按照这个例子:
set Workstation=MyVMName
call :CheckMachineUpOrDown VMStatus %Workstation%
echo %VMStatus%
如果 VM 开机,则显示 Up;如果机器关闭,则显示 Down。