4

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?

smeeb
  • 211
  • 1
  • 5
  • 13
  • 2
    Well, have you tried it? – HopelessN00b Feb 25 '15 at 18:31
  • Since this isn't documented anywhere, I would have no idea of how to even set this up inside a PS1 file or what libraries I would need to import, etc. Hence I'm wondering if doing this is even possible. – smeeb Feb 25 '15 at 18:36
  • That was kinda rhetorical... I was suggesting you try it and see what happens. Learn by doing; it's the best way. But since jscott just gave you the whole answer, never mind. :) – HopelessN00b Feb 25 '15 at 18:50

1 Answers1

11

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
...
jscott
  • 24,484
  • 8
  • 79
  • 100