Creating a Shortcut to a PowerShell Script
You’ve probably noticed that when you double-click on a PowerShell script, it is opened for editing rather than being run. This is useful from a security standpoint, and while administrators have no problem opening up the shell and running the script, you’ve probably made something useful that you want to share with users, and users always need a bit more hand-holding.

PowerShell shortcut properties
Assuming that your PowerShell installation is in the default location, you need to append the path to your script in the shortcut path like so:
%windir%\System32\WindowsPowerShell\v1.0\powershell.exe C:\Scripts\MyUsefulScript.ps1
If you are wanting to run a PowerCLI (VI Toolkit) script, you also need to add the following line:-
Add-PSSnapin VMware.VimAutomation.Core…to your script, as the VMware Cmdlets are not loaded by default unless you run it from the VMware Toolkit Shortcut.
VMware Developer CodeCentral
VMware have launched a new community site for code examples, and there’s a section on VMware vSphere PowerCLI (formerly VI Toolkit).
They seem to be picking the best scripts from the regular contributors to the forums, so it’s a good place to have a look for examples. They’re rated by users, and tend to be slightly better documented than the ones posted in the forums (which tend to be appended and amended as the thread progresses).
VMware PowerCLI 4.0 released
I came back from a week’s holiday this morning to find that VMware PowerCLI 4.0 has been released as the successor to VI Toolkit 1.5. The jump from 1.5 to 4.0 is for version number consolidation, rather than being than indicitive of major changes.
They have however fixed one of the bugs that’s been annoying me, which is the inability to change drives to non-persistent, so I’ll need to revisit some of my old scripts from v1.0 and check that they still work.
You can download it from the community page. I’ll follow up with more information when I get a chance to investigate it fully.
Add Drive Persistence State to the VI Client using Powershell
I’ve further adapted Hugo’s script to add a custom attribute which shows the drive persistence state(s) when the script was run.
The script also adds drive state information for templates as well as VM objects.
# Add drive persistence as a custom attribute for VMs and Templates $VCServerName = "MyVCServer" $VC = Connect-VIServer $VCServerName $SI = Get-View ServiceInstance $CFM = Get-View $SI.Content.CustomFieldsManager # Variables $CustomFieldName = “HD Persistence” $ManagedObjectType = “VirtualMachine” # Check if the custom field already exists $myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName} If (!$myCustomField){ # Create Custom Field $FieldCopy = $CFM.Field[0] $CFM.AddCustomFieldDef($CustomFieldName, $ManagedObjectType, $FieldCopy.FieldDefPrivileges, $FieldCopy.FieldInstancePrivileges) } # Get the machine objects $objVMs = (Get-VM) + (Get-Template) # Loop through each of the machine objects ForEach ($objVM in $objVMs){ $strPersistence = "" $objHardDisks = $objVM | Get-HardDisk # Count the number of hard drives $intHardDisks = ($objHardDisks | Measure-Object).count # Loop through each of the hard disks ForEach ($objHardDisk in $objHardDisks){ # Replace default persisstence states with initials for brevity Switch ($objHardDisk.Persistence) { Persistent { $strPersistenceInitial = "P" } IndependentPersistent { $strPersistenceInitial = "IP" } IndependentNonPersistent { $strPersistenceInitial = "INP" } } # Concatenate the initial onto the persistence string $strPersistence = "$strPersistence" + $strPersistenceInitial # If there are more hard drives to add If ($intHardDisks -gt 1) { # Append a comma and a space (there may be a more elegant way of doing this) $strPersistence = "$strPersistence" + ", " # Count down the number of hard drives $intHardDisks -= 1 } } # Add the $strPersistence to custom attribute $CustomFieldName (HD Persistence) If ($strPersistence){ $VMView = $objVM | Get-View $VMView.setCustomValue($CustomFieldName,$strPersistence) } } # End of script
Add Disk Size Information to the VI Client using Powershell
This is based on Hugo Peeters’ script to Add Snapshot Information to the VI Client using Powershell.
Our users occasionally need larger machines created for packaging big applications. After increasing the size, we used to append the VM Object name (e.g, “PACKVM01 – 10GB”), but this caused a mismatch between the virtual machine object name in VIC and the DNS host name. Also, it looked untidy!
We needed a new way for VIC users to be able to tell which were the larger machines, so I modified Hugo’s script to add disk size as a custom attribute.
# Add disk size as a custom attribute $VCServerName = “MYVCSERVER” $VC = Connect-VIServer $VCServerName $SI = Get-View ServiceInstance $CFM = Get-View $SI.Content.CustomFieldsManager # Variables $CustomFieldName = “HD Size (GB)” $ManagedObjectType = “VirtualMachine” # Check if the custom field already exists $myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName} If (!$myCustomField){ # Create Custom Field $FieldCopy = $CFM.Field[0] $CFM.AddCustomFieldDef($CustomFieldName, $ManagedObjectType, $FieldCopy.FieldDefPrivileges, $FieldCopy.FieldInstancePrivileges) } $objVMs = Get-VM ForEach ($objVM in $objVMs){ $objTotalDiskSize = 0 # Sum the total size of all disks attached to the VM ForEach ($objHardDisk in ($objVM | Get-HardDisk)){ $objTotalDiskSize += ($objHardDisk.CapacityKB/1024/1024) } If ($objTotalDiskSize){ # Round the size to one decimal place $objHDSize = "{0:N1}" -f $objTotalDiskSize $VMView = $objVM | Get-View $VMView.setCustomValue($CustomFieldName,$objHDSize) } }
Virtualization EcoShell
I’ve started looking at the recently released beta of Vizioncore’s Virtualization EcoShell, which is a VMware tailored version of PowerGUI.
Both are GUI front-ends for (among other things) VMware’s Powershell based VI Toolkit, which I’ve talked about before.
I never got the full benefit from PowerGui, as by the time I’d realised there was more to it than the (very good) script editor, I’d already developed a lot of the scripts I needed – scripts which PowerGui would have been able to generate for me a lot more quickly (c’est la vie).
EcoShell has the ability to export some nice looking reports (although the Visio based vDiagram functionality still doesn’t work for me).
There’s more information on EcoShell over at Virtua-Al.
Hal Rottenberg’s book available for pre-order
Hal Rottenberg’s book Managing VMWare Infrastructure with Windows PowerShell is now available for pre-order.
I’m a big fan of Hal‘s; he’s helped me out a few times on the VMware VI Toolkit forums. Sadly shipping to the UK is over $76, meaning that I’ll have to either wait for a digital copy, or see if a local publisher/distributer takes it up.
VI Toolkit Quick Reference
I just found Alan Renouf ‘s VI Toolkit Quick Reference [PDF], which I wish I’d seen a few months ago.
Running SQL Queries against the Virtual Center Database
In a previous post, I said that there was no real way of extracting information from the VC database.
This isn’t entirely true, as until I started using PowerShell, I was using SQL to query the VC database directly.
List XP Machines and their RAM allocation
SELECT VPX_VM.GUEST_OS, VPX_VM.MEM_SIZE_MB FROM VC_DB.dbo.VPX_VM VPX_VM WHERE (VPX_VM.GUEST_OS='winXPProGuest')
List Information about Templates
SELECT VPX_VM.LOCAL_FILE_NAME, VPX_VM.GUEST_OS, VPX_VM.IS_TEMPLATE, VPX_VM.MEM_SIZE_MB, VPX_VM.HOST_ID, VPX_VM.ID FROM VC_DB.dbo.VPX_VM VPX_VM WHERE (VPX_VM.IS_TEMPLATE=1) ORDER BY VPX_VM.LOCAL_FILE_NAME
Host names and memory
SELECT VPX_HOST.ID, VPX_HOST.DNS_NAME, CAST (VPX_HOST.MEM_SIZE AS BIGINT) FROM VC_DB.dbo.VPX_HOST VPX_HOST ORDER BY VPX_HOST.DNS_NAME
Guest Information
SELECT VPX_VM.LOCAL_FILE_NAME, VPX_VM.DNS_NAME, VPX_VM.GUEST_OS, VPX_VM.IS_TEMPLATE, VPX_VM.IP_ADDRESS, VPX_VM.MEM_SIZE_MB, VPX_VM.GUEST_STATE, VPX_VM.POWER_STATE, VPX_VM.HOST_ID, VPX_VM.ID, VPX_VM.BOOT_TIME FROM VC_DB.dbo.VPX_VM VPX_VM WHERE (VPX_VM.IS_TEMPLATE<>;1) ORDER BY VPX_VM.DNS_NAME, VPX_VM.LOCAL_FILE_NAME
These were based on ideas from Wayne’s World of IT. While it’s a lot less friendly to work with, the advantage is that it’s a lot quicker than the VI Toolkit’s Get- commands, and I still use them from time-to-time.
Although you could use this approach to modify entries in the database, I would only ever feel comfortable using this to extract information.
Introduction to using VMware vSphere PowerCLI
About 2 years ago, I moved from working as an application packager, and being responsible for two or three (VMware Workstation) virtual machines, to working on the supporting infrastructure for over 200 packagers who require around 700 virtual machines on VMware vSphere (which was at that point called VMware ESX).
While I was (and I still am) impressed by VMware’s hypervisor based virtualisation, there were a few things that started to grate with such an otherwise excellent product:-
- Performing repetitive tasks – for example setting a group of virtual hard-drives to non-persistent – using the vSphere Client GUI was time-consuming (and RSI inducing!).
- There was also no real way of extracting information from vCenter in any structured way. For example, if I wanted to know how many of our Microsoft Windows XP guests had over 512MB RAM allocated to them, they had to be counted manually.
I had a look into running scripts on the host, and toyed with the Remote CLI Appliance, but it was the VMware PowerCLI that unlocked the functionality I’d been looking for.
VMware PowerCLI (formerly VI Toolkit for Windows) utilises Windows PowerShell to provide a command-line driven interface for your virtual infrastructure. This can dramatically reduce the amount of time taken to perform almost all batch-style tasks and also enables some pretty advanced reporting functionality.
This is nowhere near a proper introduction in how to use PowerShell, but should give enough information to get you started, and hopefully make you want to find out more.
PowerCLI pre-requisites
Powershell is included in Windows 7, and Server 2008, but if it’s not included in your version of Windows, you’ll need to download and install the appropriate version of Windows PowerShell for your operating system.
Then you need to download and install VMware vSphere PowerCLI (registration required).
If you’re running PowerShell for the first time you need to change the default execution policy. To do this:
- As a user with local Administrator rights, run Windows PowerShell (on machines with UAC, right-click and Run as Administrator)
- In that window – run the command
Set-ExecutionPolicy - ExecutionPolicy RemoteSigned
This allows you to run local scripts which have not been signed with a digital signature (which will almost certainly include the scripts you’re using to learn). Scripts from remote sources will still require signing.
Security considerations
The PowerShell security model is designed to address some of the failures of VBScript – a common virus attack vector. PowerShell scripts (which have a PS1 suffix) do not run by default when invoked in Windows. Also, as noted above, the default execution policy is not to run unsigned scripts. In order to run a script, you need to modify the execution policy, and then run the script name from the command line. This helps to prevent them from being launched by accident.
In vSphere, users running PowerCLI scripts have the same permissions as they would get if they logged into vSphere Client. However, as with all scripting languages, when modifications can be made easier and faster, the potential impact of mistakes is made greater. PowerShell includes specific measures to alleviate risk, and it’s worth being familiar with this functionality before trying anything more complex.
PowerShell fundamentals
PowerShell works using cmdlets. These are typically fairly descriptive, and great care has been taken to make them work in a consistent and logical way. Most cmdlets follow the format verb-noun, with modifiers for the target of the action, and any cmdlet specific options. They are not case sensitive.
The downside of the commands being so descriptive is that they are sometimes quite long. In order to alleviate this PowerShell allows Aliases to be created. Most common Windows Shell commands already exist in PowerShell as aliases. For example CD, DIR, CLS & REN all work as expected. I find these quite useful when working interactively (entering commands at the prompt for immediate execution), but I tend to avoid them in scripts for the sake of consistency and clarity.
When launching scripts, you need to use absolute paths. For example, if you want to launch the script C:\Scripts\ExampleScript.ps1, when you’re in C:\Scripts you would either need to enter the whole path, or use ./ExampleScript.ps1.
In order to use PowerShell, you need to import the VI commands using
Add-PSSnapin VMware.VimAutomation.CoreRunning the VMware vSphere PowerCLI shortcut created when you install the application does this on launch.
![]()
Running the standard PowerShell shortcut does not.
![]()
You can however add it to your PowerShell profile, which will enable it in all PowerShell sessions, no matter which shortcut you use to launch them.
PowerShell is object-oriented, meaning that the information returned from commands can be easily used as the input for another command.
If you want to put comments into your scripts, PowerShell ignores anything after the #symbol.
Some simple Cmdlets
Here are a couple of commands to get you started. Open up the PowerCLI command line using the VMware vSphere PowerCLI shortcut, then enter them as shown.
Get-HelpCan display help on the various cmdlets. Running this as above shows the syntax for getting help.
Get-CommandUse to find out all the commands containing certain keywords. For example…
Get-Command *-VM
…uses the wildcard character (*) to show all commands that end with VM, this shows all the cmdlets that can be used to operate on Virtual Machines. Let’s try a simple one…
Get-VMYou should now get an error message saying “You are not currently connected to any servers. Please connect first using Connect-VIServer or one of its aliases.”. Let’s do that…
Connect-VIServer Name_of_your_vCenter_ServerThis uses your current windows credentials to connects to the specified server. You need to do this before you run any VMware specific PowerShell commands. Now try this again…
Get-VMYou should now be looking at a list of virtual machines managed by your vCenter server. You can reduce the scope by adding switches, for example…
Get-VM –Name A*
…gets all machines with names starting “A”. For more information, try
Get-Help Get-VM -Detailed
Variables in PowerShell are always preceded by a $ symbol. You can set a variable to the result of any kind of PowerShell command, for example, you can store the results of a Get-VM in a variable…
$objVMs = Get-VM
then use that variable any time you need it, typing
$objVMs
Will display the virtual machine objects stored in the variable. This variable is a collection of objects, each object representing a virtual machine, so we can run more commands against this variable:
Get-VMGuest -VM $objVMs
This lists the State, IP Address and guest OS of all your machine objects.
Instead of using variables for commands like this, you can also pipe the result of one command, straight into another. The equivalent of the above command, using pipes rather than variables is
Get-VM | Get-VMGuest
The objects output byt he first command are piped straight into the second command. Pipes are used extensively in PowerShell, and many cmdlets can be linked together using pipes. This means you can run some complex commands in PowerShell at the command prompt in one line, rather than resorting to writing a script.
Have a play around with these commands in your test environment before moving onto the next section. As long as you’re using Get- based commands, (rather than Set- or Remove-) you shouldn’t make any changes, but append -WhatIf and/or -Confirm to the end of your Cmdlets if you’re feeling extra-cautious.
Example scripts
Like batch files, PowerShell scripts are simply collections of commands linked together into a text file.
Here are a couple of example scripts, showing what can be done. Copy into notepad, and save with a PS1 extension. You should run Connect-VIServer interactively before running any of the scripts (or add it as the first line to the script file).
Get information about a specific machine
$strVm = Read-Host "Please enter the VM name" $vm = Get-VM -Name $strVm if ($vm.PowerState -eq "PoweredOn") { $event = Get-VIEvent -Entity $vm | Where-Object {$_.fullFormattedMessage -like "Task: Power on Virtual Machine"} $VM.Name $VM.PowerState (Get-VMGuest -VM $VM).IPAddress[0] if ($event -eq $null) { Set-Variable -Name user -Value "N/A" } else { Set-Variable -Name user -Value $event[0].username } $strMessageText = "Machine: " + $VM.Name + "`n" + "Power State: " + $VM.PowerState + "`n" + "IP Address: " + (Get-VMGuest -VM $VM).IPAddress[0] + "`n" + "Switched on by: " + $user $strMessageText } else {Write-Host "Machine not powered on"}
This script asks the user for a machine name (using Read-Host), then converts that string to a computer object, then (assuming the machine is switched on and VMware Tools is running), displays the DNS name, IP address and the username of the last user to power on the machine (as shown in the machine’s Event Log). The `n is a carriage return.
Get All Windows XP Machines with more than 2Gb of RAM
ForEach ($strMachine in (get-vm | Where-Object {$_.MemoryMB -gt "2000"})){ Get-VMGuest -VM $strMachine | Where-Object {$_.OSFullName -like "Microsoft Windows XP Professional*"} | Select-Object VMName, IPAddress }
This script could easily be modified and used as a component to make modifications on machines fulfilling certain criteria.
What else can you do?
Almost anything that can be done in the GUI can be done in PowerShell. Machines can be deployed, customized, switched on, migrated between hosts and resource pools etc. Or you could get the last time a machine was switched on, and by whom.
You can also use PowerCLI to report on the status of guests and hosts. Check out Alan Renouf’s excellent PowerCLI Daily Report, or Hugo Peeter’s script to track free space in your datastores.
One drawback of the API is that performance of cmdlets (especially Get-VM) is quite slow. Hopefully this will be addressed in future versions.
Further resources
There are many tools, example scripts and on-line resources available. Your first stop for help should be the VMware vSphere PowerCLI Community. I also recommend you keep Alan Renouf’s PowerCLI reference card close-to-hand when you’re just starting out.