您可以透過剪下、貼上和編輯 JavaScript 範例,以寫入執行一般 PowerShell 工作所需的指令碼。
如需指令碼的詳細資訊,請參閱vRealize Orchestrator《開發人員指南》。
透過 API 執行 PowerShell 指令碼
您可以使用 JavaScript 透過外掛程式 API 執行 PowerShell 指令碼。
這個範例指令碼執行下列動作。
- 開啟 PowerShell 主機的工作階段。
- 提供執行的指令碼。
- 檢查叫用結果。
- 關閉工作階段。
var sess;
try {
//Open session to PowerShell host
var sess = host.openSession()
//Set executed script
var result = sess.invokeScript('dir')
//Check for errors
if (result.invocationState == 'Failed'){
throw "PowerShellInvocationError: Errors found while executing script \n" + result.getErrors();
}
//Show result
System.log( result.getHostOutput() );
} catch (ex){
System.error (ex)
} finally {
if (sess) {
//Close session
host.closeSession( sess.getSessionId() );
}
}
處理結果
您可以使用 JavaScript 處理 PowerShell 指令碼執行的結果。
這個範例指令碼執行下列動作。
- 檢查叫用狀態。
- 從結果擷取值。
- 檢查 RemotePSObject 類型。
var sess = host.openSession()
sess.addCommandFromString("dir " + directory)
var invResult = sess.invokePipeline();
//Show result
System.log( invResult.getHostOutput() );
//Check for errors
if (invResult.invocationState == 'Failed'){
System.error(invResult.getErrors());
} else {
//Get PowerShellRemotePSObject
var psObject = invResult.getResults();
var directories = psObject.getRootObject();
var isList = directories instanceof Array
if ( isList ){
for (idx in directories){
var item = directories[idx];
if ( item.instanceOf('System.IO.FileInfo') ){//Check type of object
System.log( item.getProperty('FullName') );//Extract value from result
}
}
} else {
System.log( directories.getProperty('FullName') );//Extract value from result
}
}
host.closeSession( sess.getSessionId());
使用自訂認證進行連接
您可以使用 JavaScript 透過自訂認證連線到 PowerShell 主機。
var sess;
try {
sess = host.openSessionAs(userName, password);
var invResult = sess.invokeScript('$env:username');
//Check for errors
if (invResult.invocationState == 'Failed'){
System.error(invResult.getErrors());
} else {
//Show result
System.log( invResult.getHostOutput() );
}
} catch (ex){
System.error (ex)
} finally {
if (sess) {
host.closeSession( sess.getSessionId());
}
}