So I've written a PowerCLI script to use with apcupsd to shutdown any VMs running on NAS datastores and shut them down first (so the NAS can then shut down).
Here's a cut down version of the script - ignore the variables that aren't initialised, gets pulled from a file and works fine but clutters things up so I took it out. When I run this from the command line, it works perfectly. Does exactly what I want it to do.
#!/usr/bin/powershell/pwsh
Write-Output "PS Environment Variables: "
Write-Output $Env:PSModulePath
$server = $($item.SERVER)
$user = $($item.USER)
$pass = ConvertTo-SecureString $($item.PASSWORD) -AsPlainText -Force
# Create credential object
$pscreds = New-Object System.Management.Automation.PSCredential ($user, $pass)
# Connect to server
Connect-VIServer $server -Credential $pscreds
# Find any datastore with NAS as part of the name, grab any running VM's and issue a guest shutdown
Get-Datastore | Where{$_.name -like '*NAS*'} | Get-VM | Where{$_.PowerState -eq 'PoweredOn'} | Shutdown-VMGuest -Confirm:$false
But when I then add it to the APCUPSD config it gets called when it's supposed to.. and fails with the following output:
PS Environment Variables:
/tmp/9d12ecbf-5362-4faa-98a3-d45f001a03c5/.local/share/powershell/Modules:/usr/local/share/powershell/Modules:/usr/bin/powershell/Modules
Directory: /usr/bin/powershell/Modules
ModuleType Version PreRelease Name PSEdition
---------- ------- ---------- ---- ---------
Script 12.5.0.19… VMware.CloudServices Desk
<snip - lists all modules>
Script 12.1.0.16… VMware.VumAutomation Desk
Connect-VIServer: /root/scripts/VMShutDown/test.ps1:16
Line |
16 | Connect-VIServer $server -Credential $pscreds
| ~~~~~~~~~~~~~~~~
| The 'Connect-VIServer' command was found in the module
| 'VMware.VimAutomation.Core', but the module could not be
| loaded. For more information, run 'Import-Module
| VMware.VimAutomation.Core'.
Get-Datastore: /root/scripts/VMShutDown/test.ps1:19
Line |
19 | Get-Datastore | Where{$_.name -like '*NAS*'} | Get-VM | Where{$_. …
| ~~~~~~~~~~~~~
| The type initializer for
| 'VMware.VimAutomation.Sdk.Interop.V1.CoreServiceFactory' threw
| an exception.
No difference other than it's being run by apcupsd so my thought was some kind of environment variable missing, but I specifically installed the module into the /usr/bin/powershell/Modules directory with the following, and it works just fine when called via the command line
Find-Module -Name 'VMware.PowerCLI' -Repository 'PSGallery' | Save-Module -Path /usr/bin/powershell/Modules
Import-Module -FullyQualifiedName '/usr/bin/powershell/Modules/VMware.PowerCLI'
So pretty stumped. Any ideas welcome.