Can vSphere PowerCLI cmdlets execute from a PS1 file?

6,998

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
...
Share:
6,998

Related videos on Youtube

smeeb
Author by

smeeb

Updated on September 18, 2022

Comments

  • smeeb
    smeeb over 1 year

    I'm looking to write an admin script that will:

    • Delete a VM from vSphere
    • Delete the VM's DNS entry
    • Release the VM's IP address with our Windows DHCP server

    I can accomplish the first item via vSphere's PowerCLI, and I can accomplish the last 2 items via PowerShell "Cmdlets". Furthermore I can put these Cmdlets inside a *.ps1 file and execute the file from the shell.

    Initial research shows the PowerCLI just wraps/extends PowerShell, and is basically just composed of its own vSphere-centric Cmdlets. So I'm wondering: can I put PowerCLI "code" (Cmdlets, etc.) inside a PS1 file, along with other PowerShell code, and execute it like a normal PS1?