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.chapter4from recipe 4.1, and recipe 4.3 for how polyglot actions run. - The vCenter
vc01.vmw.labwith 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
- In Library > Actions, create the action
formatUptimein the modulecom.vcfguide.chapter4. - On the Script tab, set the Runtime Environment to PowerShell 7.6. Add one input,
seconds, of typenumber, and set the Return type tostring. - The editor fills in a sample
Handlerfunction. Replace it with this script and click Save:
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}- Run it with
seconds=273600. The result is3 days, 4 hours, 0 minutes, and the log shows theWrite-Hostline.

See what stray output does
- Add one line before
return $text, as if you were checking a value while writing the script:
$span.TotalHours- 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 saysstring. Nothing warns you. Delete the line again. Whenever a command writes something you don’t want, send it toOut-Null, or useWrite-Hostto log it.
A PowerCLI action that connects to vCenter
-
Create the action
getSnapshotReportincom.vcfguide.chapter4. On the Script tab, set the Runtime Environment to PowerCLI 9.1.1 (PowerShell 7.6). -
Add four inputs:
vcenter(string),user(string),password(SecureString), andmaxAgeDays(number). Set the Return type toProperties. -
Raise the limits before the first run: set Memory limit to
512MB and Timeout to300seconds. 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,512is what you’ll see.

- Enter this script and click Save:
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 }}- Run it with
vcenter=vc01.vmw.lab,user=svc-vcfguide-ro@vsphere.local, the password, andmaxAgeDays=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, andreporthas one line for each.

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
SecureStringinput arrives in PowerShell as a plain string, soConnect-VIServer -Password $inputs.passwordworks 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 $falseat session scope. The notice is printed while the module loads, before your script can change the setting. It’s harmless.
Call it from JavaScript
- The snapshot report and the uptime text can be used from any JavaScript script, like other actions:
var chapter4 = System.getModule("com.vcfguide.chapter4");
// vm (VC:VirtualMachine), vcenterUser (string), and vcenterPassword (SecureString)// are inputs of the scriptvar 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.
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.
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.
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.
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
- 4.9 Reading inputs in Python, Node.js and PowerShell, for how each input type arrives in every runtime.
- 4.3 Python actions and environments, for how polyglot actions run and how environments get their packages.
- 4.7 Working with configuration elements in code, which keeps the vCenter account out of the action’s inputs.
- 1.9 Registering your first vCenter, for the vCenter plug-in, which is the JavaScript way to do the same work.
- Broadcom TechDocs (VCF 9.0): Scripting Environments in VCF Operations Orchestrator, Configuring Scripting Environments, and Runtime Limits for Scripts.
- Broadcom community: PowerShell action hitting an out-of-memory condition and vRO PS return bug, on memory and on cmdlet output in the return value.
- Broadcom developer documentation: VCF PowerCLI. PowerShell Gallery: VCF.PowerCLI.
- Microsoft: about_Return and about_Output_Streams, on why a function returns its whole output.
- CloudBlogger, the author’s blog: VCF Operations Orchestrator 9.0.2: List of PowerShell and PowerCLI Modules, SQLServer PowerShell module available via Orchestrator Environments.
