我知道它的晚来回答这个问题一点点,但我想尝试一下,以防万一任何一个需要更详细的解决方案。所以,在这里。
我创建了一个批处理功能将执行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>
Powershell Set-ExecutionPolicy RemoteSigned -Force
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是向上或向下,如果是开机还是关机的意思,所以我们可以做到以下几点:
: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>
Powershell Set-ExecutionPolicy RemoteSigned -Force
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%
这将显示截至如果虚拟机启动或停机如果机器关闭。
希望这是有帮助的。
谢谢
很好的解决方案。我怀疑有没有其他的那么简单直接。 – stej 2010-08-05 14:46:46
感谢您的回复,但我不认为上述方法可行?我期望在这种情况下发生的事情是,环境变量'd'的值将是'powershell -noprofile“&{get-date}”'。 IE:不评估表达式右侧的内容。 – 2010-08-05 15:02:48
@尼古拉斯,你是对的。我现在已经试过了,只有字符串存储在变量中。 – stej 2010-08-05 15:30:01