您可以剪切、粘贴和编辑 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());
}
}