Skip to content

PowerShell and PowerCLI actions

Many VMware administrators already have a drawer full of PowerCLI scripts. Orchestrator can run them as they are, almost: the PowerShell runtime runs PowerShell 7.6, and the PowerCLI runtime adds the VMware modules on top. That makes a PowerCLI action the shortest path from “I have a script that does this” to “a workflow does this, with a form, permissions, and a log”.

PowerShell has two habits that trip people up in Orchestrator. Everything a function outputs becomes part of what it returns, not just the value after return. And connecting to vCenter loads a lot of code, which doesn’t fit in the default memory limit. In this recipe you write a small PowerShell action to see the first, then a PowerCLI action that lists old snapshots, and you deal with both.

Getting ready

  • The action module com.vcfguide.chapter4 from recipe 4.1, and recipe 4.3 for how polyglot actions run.
  • The vCenter vc01.vmw.lab with a few VMs, ideally one with a snapshot.
  • A vCenter account with read-only rights for the PowerCLI action. The examples use svc-vcfguide-ro@vsphere.local. Recipe 4.7 moves its password into a configuration element. For now you type it in.

How to do it

A first PowerShell action

  1. In Library > Actions, create the action formatUptime in the module com.vcfguide.chapter4.
  2. On the Script tab, set the Runtime Environment to PowerShell 7.6. Add one input, seconds, of type number, and set the Return type to string.
  3. The editor fills in a sample Handler function. Replace it with this script and click Save:
com.vcfguide.chapter4/formatUptime
function Handler($context, $inputs) {
# Turns a number of seconds into text such as "3 days, 4 hours, 12 minutes".
$span = [TimeSpan]::FromSeconds([double]$inputs.seconds)
$text = "{0} days, {1} hours, {2} minutes" -f $span.Days, $span.Hours, $span.Minutes
Write-Host "Uptime of $($inputs.seconds) seconds is $text"
return $text
}
  1. Run it with seconds = 273600. The result is 3 days, 4 hours, 0 minutes, and the log shows the Write-Host line.
Script tab of action formatUptime: Runtime Environment PowerShell 7.6, Type Script, the Handler function that turns seconds into days, hours and minutes, return type string, one input seconds of type number, Memory limit 150 MB and Timeout 180 seconds.
Figure 4.13. A PowerShell action: the runtime, a typed input, and the Handler function.

See what stray output does

  1. Add one line before return $text, as if you were checking a value while writing the script:
A line that changes the return value
$span.TotalHours
  1. Run it again. It doesn’t fail, but the result is wrong: the action now returns two values, the number of hours and the text. On 9.1.1, a run from the editor shows an empty result, and a JavaScript caller gets an array, [76, "3 days, 4 hours, 0 minutes"], even though the return type says string. Nothing warns you. Delete the line again. Whenever a command writes something you don’t want, send it to Out-Null, or use Write-Host to log it.
Needs a lab check. Checked on 9.1.1: the runtime label PowerShell 7.6 and the results of steps 4 and 6. Still to check: the sample code the editor fills in for a new PowerShell action.

A PowerCLI action that connects to vCenter

  1. Create the action getSnapshotReport in com.vcfguide.chapter4. On the Script tab, set the Runtime Environment to PowerCLI 9.1.1 (PowerShell 7.6).

  2. Add four inputs: vcenter (string), user (string), password (SecureString), and maxAgeDays (number). Set the Return type to Properties.

  3. Raise the limits before the first run: set Memory limit to 512 MB and Timeout to 300 seconds. The default of 150 MB is too little for loading PowerCLI and connecting to vCenter.

    The field counts in decimal megabytes. The lab’s action was saved through the REST API, which takes the limit in bytes (512 MiB = 536,870,912 bytes), so Figure 4.14 shows 536.870912. Typed in the client, 512 is what you’ll see.

Script tab of action getSnapshotReport: Runtime Environment PowerCLI 9.1.1 (PowerShell 7.6), the Handler script with Set-PowerCLIConfiguration, Connect-VIServer, Get-Snapshot and a finally block that disconnects, return type Properties, inputs vcenter, user, password (SecureString) and maxAgeDays, Memory limit 536.870912 and Timeout 300 seconds.
Figure 4.14. A PowerCLI action with its memory limit raised for connecting to vCenter.
  1. Enter this script and click Save:
com.vcfguide.chapter4/getSnapshotReport
function Handler($context, $inputs) {
# Lists snapshots older than maxAgeDays on one vCenter. Reads only.
$maxAge = [int]$inputs.maxAgeDays
if ($maxAge -le 0) { $maxAge = 7 }
# Session-only settings. Out-Null keeps their output out of the return value.
Set-PowerCLIConfiguration -Scope Session -ParticipateInCeip $false `
-InvalidCertificateAction Ignore -Confirm:$false | Out-Null
$server = Connect-VIServer -Server $inputs.vcenter -User $inputs.user `
-Password $inputs.password -ErrorAction Stop
try {
$cutoff = (Get-Date).AddDays(-$maxAge)
$old = Get-VM -Server $server | Get-Snapshot -Server $server |
Where-Object { $_.Created -lt $cutoff } | Sort-Object Created
$lines = @()
foreach ($snap in $old) {
$days = [int]((Get-Date) - $snap.Created).TotalDays
$lines += "{0}: '{1}', {2} days old, {3:N1} GB" -f $snap.VM.Name, $snap.Name, $days, $snap.SizeGB
}
Write-Host "$($lines.Count) snapshots older than $maxAge days on $($inputs.vcenter)"
return @{
vcenter = $inputs.vcenter
maxAgeDays = $maxAge
count = $lines.Count
report = ($lines -join "`n")
}
}
finally {
Disconnect-VIServer -Server $server -Confirm:$false | Out-Null
}
}
  1. Run it with vcenter = vc01.vmw.lab, user = svc-vcfguide-ro@vsphere.local, the password, and maxAgeDays = 7. The first run takes noticeably longer than later ones while the PowerCLI modules load. The result shows how many snapshots are older than a week, and report has one line for each.
Logs tab of a completed run of Report old snapshots: the PowerCLI CEIP notice, then 1 snapshots older than 7 days on vc01.vmw.lab written by the action, and 1 snapshots older than 7 days written by the workflow.
Figure 4.15. The PowerCLI action at work: its Write-Host line in the log of a run that calls it (the workflow from recipe 4.7).

Checked on 9.1.1 in the lab:

  • The runtime is PowerCLI 9.1.1 (PowerShell 7.6); in the action’s REST definition it’s powercli:9.1.1-powershell-7.6.
  • 512 MB is enough to load PowerCLI, connect, list snapshots and disconnect. A run took 15 to 20 seconds.
  • A SecureString input arrives in PowerShell as a plain string, so Connect-VIServer -Password $inputs.password works as written.
  • The hashtable comes back to a JavaScript caller as Properties: report.get("count") works, as in step 12.
  • PowerCLI still prints its CEIP notice, about ten lines, to the log on every run, even with -ParticipateInCeip $false at session scope. The notice is printed while the module loads, before your script can change the setting. It’s harmless.

Call it from JavaScript

  1. The snapshot report and the uptime text can be used from any JavaScript script, like other actions:
Calling the PowerShell actions from JavaScript
var chapter4 = System.getModule("com.vcfguide.chapter4");
// vm (VC:VirtualMachine), vcenterUser (string), and vcenterPassword (SecureString)
// are inputs of the script
var uptime = chapter4.formatUptime(vm.summary.quickStats.uptimeSeconds || 0);
System.log(vm.name + " has been up for " + uptime);
var report = chapter4.getSnapshotReport("vc01.vmw.lab", vcenterUser, vcenterPassword, 7);
if (report.get("count") > 0) {
System.warn(report.get("count") + " old snapshots:\n" + report.get("report"));
}

How it works

A PowerShell or PowerCLI action runs in its own container, like Python and Node.js. Orchestrator turns the inputs into JSON, starts PowerShell 7.6, loads your script, and calls the function Handler with $context and $inputs. Read inputs as $inputs.seconds or $inputs["seconds"]. PowerShell function names aren’t case-sensitive, so Handler and handler are the same function.

What a PowerShell function returns. In most languages a function returns what follows return. In PowerShell, a function returns its whole output stream: every value that a line produces and doesn’t assign, pipe on, or send to Out-Null, plus the value after return. One value comes back as itself. Two or more come back as an array. That’s why step 5’s bare $span.TotalHours broke the action, and why Set-PowerCLIConfiguration and Disconnect-VIServer, which both write objects, end with | Out-Null. Write-Host writes to a different stream, the information stream, so its lines go to the run’s log without touching the result.

PowerCLI versus PowerShell. The two runtimes run the same PowerShell. The PowerCLI runtime adds modules: in 9.0, Broadcom lists VMware PowerCLI 13, PowerNSX, and PowervRA. With the plain PowerShell runtime you start with only what PowerShell itself has, and add modules from the PowerShell Gallery or another NuGet v2 feed through an environment.

Memory. The defaults for PowerShell and PowerCLI are 150 MB and 180 seconds. That’s enough for formatUptime, but PowerCLI is large. Importing it and connecting to vCenter takes more memory than many scripts do afterwards, and a run that goes over the limit is stopped with an out-of-memory error, often with no hint that memory was the cause. Community reports from 8.x needed 256 to 512 MB for a connection and a few changes. Start at 512 MB and lower it once you know what the action uses.

Sessions don’t last. Every run starts a fresh PowerShell. Nothing survives between runs, including Connect-VIServer sessions and Set-PowerCLIConfiguration settings with -Scope Session. So each run connects, works, and disconnects, as in step 10. The finally block makes sure the vCenter session is closed even when the work in try fails, so you don’t leave idle sessions behind on vCenter.

Back in vRO 5.5–7Install a Windows host with PowerShell and PowerCLI, register it with the PowerShell plug-in over WinRM, and send it scripts as text. Keep the modules on that host up to date yourself.
In Orchestrator 9.xChoose the PowerShell 7.6 or PowerCLI runtime for an action. The script runs in a container on the appliance, with no Windows host, and returns typed values.

There's more

“The proxy tunnel request … failed with status code ‘503’”. On an embedded Orchestrator, script runtimes reach other hosts through a proxy inside VCF Automation, proxy-service.prelude.svc.cluster.local:3128. When Connect-VIServer names a host that proxy can’t reach, for example a name that doesn’t resolve, the error is about the proxy, not about vCenter. Check the host name first: in the lab this came from running Report old snapshots (recipe 4.7) with the book’s sample name vc01.vmw.lab, which doesn’t exist there.

Checked on an embedded Orchestrator 9.1.1, inside VCF Automation, 1 Dec 2026. The proxy address and the 503 answer for a host it can’t reach, from the run’s log.

Don’t ignore certificates in production. -InvalidCertificateAction Ignore lets the lab work with vCenter’s VMCA certificate, which the container doesn’t trust. In production, make the container trust your CA or use vCenter’s own certificate trust settings. A certificate check that’s switched off hides a man-in-the-middle as well as a self-signed certificate.

Needs a lab check. Check whether the PowerCLI runtime on 9.1.1 trusts the certificates in Orchestrator’s own trust store (vracli vro keystore list, recipe 1.8), which would make Ignore unnecessary for vCenters already registered with the vCenter plug-in.

Use Write-Host for log lines. Write-Host lines appear on the run’s log. Write-Output and bare values go into the return value instead. Write-Warning and Write-Error write to their own streams. Recipe 4.6 checks how each one shows up on the log.

Format tables for the log. Format-Table produces formatting objects, not text, and its output doesn’t appear on the log. Send it to the host: Get-VM | Format-Table Name, PowerState | Out-Host.

Newer PowerCLI. If you need a PowerCLI release newer than the one in the runtime, for example the VCF PowerCLI 9 modules, create an environment on the plain PowerShell 7.6 runtime and add VCF.PowerCLI from the PowerShell Gallery as a dependency. It’s a large download with many modules, so the environment build takes a while, and the action needs even more memory.

Needs a lab check. Build a PowerShell 7.6 environment on 9.1.1 with VCF.PowerCLI as a dependency and record the build time, whether Connect-VIServer works from it, and the memory limit it needs.

Return a few typed values, not objects. A PowerCLI object such as a VM or snapshot can’t cross back into Orchestrator. Return a hashtable of strings, numbers, and booleans, as in step 10, or an array of such hashtables. If you need the VM as a VC:VirtualMachine object afterwards, return its name or its managed object ID, and look it up in JavaScript.

Debugging. PowerShell and PowerCLI scripts can’t be debugged from an external IDE. Develop the body of the script in a local PowerShell 7.6 with the same PowerCLI version, then wrap it in Handler.

See also