Can vSphere PowerCLI cmdlets execute from a PS1 file?
Solution 1:
can I put PowerCLI "code" (Cmdlets, etc.) inside a PS1 file, along with other PowerShell code, and execute it like a normal PS1?
Yes. But if you want it to work as expected (as when you use the PowerCLI console) you'll need to initialize the environment. You can see how this is done by examining the shortcut "VMware vSphere PowerCLI.lnk", the target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -psc "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -noe -c ". \"C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\""
Breaking this down:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
The Powershell binary
-psc "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1"
Short for -PSConsole
, which loads the vim.psc1 console specified.
-noe
Short for -NoExit
, don't close after running the startup commands.
-c ". \"C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\""
Short for -Command
, which dot sources the [note path is escape-quoted] file Initialize-PowerCLIEnvironment.ps1 into the session.
You can condense this and put the initialization into any .ps1 file. This stub example should get you started.
# This is the main magic.
Add-PSSnapin VMware.VimAutomation.Core
# Dot source the PowerCLI init script
. 'C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1'
# We're up and running with "PowerCLI", do some VM stuff.
Connect-VIServer vcenter-01
Get-VM
...