VMware: PowerCli Scripts in native Powershell

Hi,

when you want to execute your PowerCli script you have to start the “VMware vSphere PowerCLI” shell before. But, for example Schedule Tasks, it whould be nice that the script load the PowerCli environment itself. Then you simply have to start your script like this

%Systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -File YourPowerCliScript.ps1

To load the PowerCli script Environent in your powershell script add this lines at the top of your script.

Add-PSSnapin VMware.VimAutomation.Core
Add-PSSnapin VMware.VimAutomation.Vds
if(get-item HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\VMware.VimAutomation.Core){
	. ((get-item HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\VMware.VimAutomation.Core).GetValue("ApplicationBase")+"\Scripts\Initialize-PowerCLIEnvironment.ps1")
}
else
{
	write-warning "PowerCLI Path not found in registry, please set path to Initialize-PowerCLIEnvironment.ps1 manually. Is PowerCli aleady installed?"
	. "D:\Programs (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
}

# Connect to vCenter
$sVCenterHost="vcenter.subdomain.domain.local"
Write-Host -NoNewline " Connecting to vCenter..."
Connect-VIServer $sVCenterHost -ErrorAction SilentlyContinue -WarningAction SilentlyContinue |out-null
if(!$?){
	Write-Host -ForegroundColor Red " Could not connect to $sVCenterHost"
	exit 2
}
else{
	Write-Host "ok"
}

The script reads the PowerCLI installation path from the registry, load the snapins VMware.VimAutomation.Core and VMware.VimAutomation.Vds and executes Initialize-PowerCLIEnvironment.ps1 in the current shell (the leading “.” is importent)

Have fun

Michael

2 thoughts on “VMware: PowerCli Scripts in native Powershell”

Leave a Reply Cancel reply