我知道它的晚來回答這個問題一點點,但我想嘗試一下,以防萬一任何一個需要更詳細的解決方案。所以,在這裏。
我創建了一個批處理功能將執行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