You can cut, paste, and edit the JavaScript examples to write scripts for common PowerShell tasks.
For more information about scripting, see the vRealize Orchestrator Developer's Guide.
Run a PowerShell Script Through the API
You can use JavaScript to run a PowerShell script through the plug-in API.
This example script performs the following actions.
- Opens a session to a PowerShell host.
- Provides a script to run.
- Checks invocation results.
- Closes the session.
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() ); } }
Work with Result
You can use JavaScript to work with the result of a PowerShell script run.
This example script performs the following actions.
- Checks the invocation state.
- Extracts a value from the result.
- Checks the RemotePSObject type.
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());
Connect with Custom Credentials
You can use JavaScript to connect to a PowerShell host with custom credentials.
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()); } }