Archives For Powershell

I recently found myself investigating a problem with a distributed virtual switch after some unplanned downtime of a vCenter due to a power cut. The problem with the DVS was quickly resolved after bringing the vCenter back up but I had a number of VM’s that were powered up but not connected to the network.

With my new found love for powershell I whipped up a one liner to report on the VM’s that were disconnected from the network.

Get-NetworkAdapter (get-vm | where {$_.powerstate -eq “poweredon”}) | Where { $_.connectionstate.connected -eq “$F” } | select parent, connectionstate

One part that confused me was the Where { $_.connectionstate.connected -eq “$F” } I found if I wrote $False it would give me the results I wanted but $F did, thats one for me to ask the PowerCLI guru’s.

As there were only a couple of VM’s with NICs disconnected I went and set them online manually, but I could have easily done that with PowerCLI as well.

UPDATE

As Alan kindly explained in the comments below

$flase is a pre-defined variablem if you type $false at the PowerShell prompt you will see it return False but $f is just an empty variable, if you type $f at the cmd prompt it will return anything, I normally use $null just as a default so people know it means nothing.

So the script to make more sense when reading through it could be changed to look like this

Get-NetworkAdapter (get-vm | where {$_.powerstate -eq “poweredon”}) | Where { $_.connectionstate.connected -eq “$null” } | select parent, connectionstate

Many thanks to Alan once again for putting me on the correct track with PowerCLI.

Learning Powershell

February 9, 2011 — 1 Comment

Why I  wanted to learn Powershell

When installing and managing virtual infrastructures there are lots of repetitive tasks, when repetitive tasks are involved there is always the chance for mistakes. Mid last year I was working on sets of standards for installing and managing virtual infrastructures and it seemed the obvious progression to be able to automate some of these processes. This allowed me to help set standards and use time in a more intelligent manner.

Also in the era of “The Cloud” and “IT as a Service” the view of IT departments is starting to look increasingly on how we can streamline operations, offer automated workflows and deliver IT to the business as they need it.

 

The Who

Whilst attending the London VMUG in October last year I attended Alan Renouf’s Powershell session, I had also attended his session earlier in the year at a previous VMUG. What was different about this session is Alan had made it interactive, setting a number of tasks and allowing us all to connect into his home lab to try the scripts / one liners we had written. This is very much the way I learn, by being able to get hands on and try something make mistakes and correct them I absorb a lot more than simply reading a book or listening to a presentation. There was also a further bonus that I managed to persuade Jonathan Medd, Microsoft Powershell MVP to join our group for these tasks, Jonathan was very patient with my lack of knowledge and  explained a lot of the key elements of Powershell to me whilst we were working through the tasks.

I owe a lot of thanks to these guys for their help, their blogs and the passion for Powershell that they have passed onto me.

If you are wanting to learn more about Powershell be sure to check these guys blogs out

Alan Renouf – http://www.virtu-al.net

Jonathan Medd – http://www.jonathanmedd.net/

They have also been working on a book with a number of other Powershell / VMware experts that is due to be released in the next few months, more information can be found at the links below.

The website for the book – http://www.powerclibook.com/

Amazon – http://www.amazon.co.uk/VMware-VSphere-PowerCLI-Reference-Administration/dp/0470890797/ref=sr_1_1?ie=UTF8&qid=1296977693&sr=8-1

 

The How

Understand what you have to work with

A good place to start is by understanding the cmdlets you have to work with, the cmdlets are made up of a verb and a noun such as get-command and are the essence of what makes Powershell so user friendly when it comes to getting started. Different manufacturers will produce cmdlets for their products, you may have guessed already as you are reading this on my blog, but I will tend to focus on the VMware cmdlets, that are packaged as PowerCLI.

A good place to start to achieve this is the PowerCLI poster — http://www.virtu-al.net/2010/08/25/powercli-4-1-poster-and-quick-reference-guide/

Powercliposter

With thanks to Jonathan Medd I have one of these on my office wall, which is always good to refer to whilst scripting.

The second way to get a rundown of the cmdlets is to run Get-VICommand from a PowerCLI window. This will list all the PowerCLI Cmdlets

Get vicommand

To get more information about anyone of these Cmdlets use the get-help [cmdlet name] -examples command

Get help

If you are in a situation where you don’t know the cmdlet you wish to use, you can always call upon get help using wildcards, for example if we wanted to create a virtual switch but didn’t know the cmdlet we could use

Get-Help *switch*

This would give us the following results

Get help2

We could then run Get-Help New-VirtualSwitch – Examples to find out how we use the cmdlet.

If you are looking for a run down of the Powershell 2.0 Cmdlets I would highley recommends Jonathan’s One Cmdlet at a time blog series and PDF.

http://www.jonathanmedd.net/tag/cmdlet-series

Set yourself tasks or challanges

I found getting started learning Powershell to be quite challenging to start with as I couldn’t think of what to script. There are so many good scripts already out there already, that coming up with something original was a challenge. Just because there is a script already completed don’t let this put you off writing your own, you can then use the other scripts as inspiration or assistance when you get stuck.

VMworld PowerCLI Lab Manuals –

VMware have published the lab manual from VMworld 2010 on their PowerCLI blog, this is a very good document that not only has some challenges but also has the answers and explanations.

http://blogs.vmware.com/vipowershell/2010/11/vmworld-2010-powercli-lab-manual-for-your-reading-pleasure-alton-yu.html

There is also a similar document for 2009

http://blogs.vmware.com/files/vi-toolkit-lab—-vmworld-europe-2009.pdf

One of my challenges was to configure my new home lab server completely using PowerCLI, this gave me a good understanding of the PowerCLI Cmdlets

Have a lab

The key of being able to get your head around Powershell is being able to test your scripts before running them on a production environment. This can be a lot easier than it sounds, there are numerous examples of VMware Home Labs on the blogosphere, they could be made up of anything from ESX host in VMware Workstation, an affordable server to a spare blade in a production environment. If you are using the lab to test and build Powershell scripts the performance doesn’t usually matter all that much. I was able to roll out 30+ VM’s on my Microserver to test scripts, of course these servers had very small memory, cpu and disk requirments because I wasn’t worried about having an OS running, just the VM’s to manipulate, create and delete etc.

My home lab

https://virtualisedreality.com/2010/02/14/home-lab/

https://virtualisedreality.com/2010/08/07/home-lab-update/

https://virtualisedreality.com/2010/12/10/home-lab-update-3/

Further home labs

http://www.techhead.co.uk/vmware-esxi-home-lab-why-what-and-how-considerations-when-building-your-own-home-lab

http://www.yellow-bricks.com/2010/01/19/my-homelab/

There are also lots more examples that you will find my googling “VMware Home Lab” http://tinyurl.com/622kuyb

Training Material

As I have mentioned before I learn best when someone is able to walk through something with me, give me examples etc. That’s why I always find TrainSignal training so good,

TrainSignal have a number of Powershell elements in there vSphere series, I can highly recommend the vSphere Pro Training volumes 1 and 2. The Powershell elements are instructed by Hal Rottenburg (Microsoft Powershell MVP) and I found them really informative and meant I was able to follow along with the videos.

Vsphere pro series vol2 able

Hal also has a book available

Halsbook

http://www.amazon.co.uk/Managing-VMware-Infrastructure-Windows-Powershell/dp/0982131402/ref=sr_1_3?ie=UTF8&qid=1296983541&sr=8-3

VMware also have a Training Course that covers PowerCLI – VMware vSphere: Automation with vSphere PowerCLI [V4.x]

http://mylearn.vmware.com/mgrreg/courses.cfm?ui=www_edu&a=one&id_subject=19082

I haven’t been lucky enough to attend this course, but would love to!

Powershell / PowerCLI Blogs

VMware PowerCLI Blog – http://blogs.vmware.com/vipowershell/

Alan Renouf – http://www.virtu-al.net/

Jonathan Medd – http://www.jonathanmedd.net/

Luc D’s – http://www.lucd.info/

Hugo Peeters – http://www.peetersonline.nl/

Hal Rottenburg – http://halr9000.com/


The Tools

When I started trying to learn Powershell, I started by typing scripts in the Powershell console and trying to build my scripts in Notepad. This really doesn’t work very well and when I found a good script editor it changed my ability to write and troubleshoot scripts. I am personally using the PowerGUI Script Editor mainly because I already had it installed with the PowerGUI program itself.

Powergui

Creating Scripts

I have found it easiest to create scripts by breaking it down into a number of smaller code blocks, addressing each of the goals one at a time, you can then concentrate on bringing the separate blocks together at the end. Whilst writing your scripts ensure you add meaningful comments as you go, this won’t only help others that may need to use the script but will help you when you come back to it 6 months later.

I hope you have found this blog post useful, please feel free to share your thoughts, tips and tricks.

 

 

I have been working on this script on and off for a couple of weeks, the plan was to get my head around the new Equallogic Powershell tools and create a configuration dump that could be used to assist with documenting / analysing an Equallogics configurations. I also used this as a point to have a play with SAPIEN Technologies PrimalForms (Community Edition).

I have created a script which is linked to below. Please be aware this is currently a beta and I am looking for as much feedback on this as possible. The script will display a GUI to allow you to type the connectivity information

image

The script will check for the existence of the HIT Kit 3.5 or higher, if it is not present it will alert you.

image

The script checks for the existence of a folder called EqlReports on the root of the C: drive, if it doesn’t exist it will create it. The report once created it named GroupName-Report-Date. So if you are testing the same SAN on the same day you will need to rename the files.

The final report is a HTML based report and will look something like this.

image

It includes, group, replication, member, volume, volume acl, snapshot and schedule information. Currently the IP’s are displayed in IPV6 but in v2 I will add the IPV6 conversion.

The main Powershell one liners that are used are as below.

Group Configuration

Get-EqlGroupConfiguration | select groupname, groupaddress, grouptimezone,
 groupdescription, smtpservers, grouplocation, ntpservers 

Replication Parther

Get-EqlReplicationPartner | select partnername, partneripaddress, 
partnerdescription, primarygroup, delegatedspacemb, replicationstatus |
 ConvertTo-Html -pre "<h1>Replication Partner</h1> "  -Fragment

Member Information

get-eqlmember | select membername, memberdescription, firmwareversion, 
defaultgateway, storagepoolname, raidtype, raidstatus, totalspacemb, 
freespacemb | ConvertTo-Html -pre "<h1>Member Information</h1> " -Fragment

Volume Information

get-eqlvolume | select volumename, volumesizeMB, StoragePoolName, 
ThinProvision, onlinestatus, volumedescription, snapshotreservepercent, 
replicareserveinuseMB, snapshotcount | ConvertTo-Html 
-pre "<h1>Volume Information</h1> "  -Fragment

Volume ACL Information

get-eqlvolume | get-eqlvolumeacl | select volumename, initiatorname,
 username, initiatoripaddress, acltargettype | ConvertTo-Html 
-pre "<h1>Volume ACL Information</h1> "  -Fragment

Snapshot Information

get-eqlvolume | get-eqlsnapshot | select volumename, snapshotname, 
snapshotsizemb, onlinestatus, creationtimestamp | ConvertTo-Html
-pre "<h1>Snapshot Information</h1> "  -Fragment

 

Finally a bit more indepth was the schedule information, I only wanted the data for volumes with schedules, otherwise you got nasty blank information with only titles. Big thanks must goto @virtualportal Steve Bryenn http://virtual-portal.com for assisting me with this code

 $sched = @()
 $volumes = get-eqlvolume 
 foreach ($volume in $volumes)
 {
     $schedules = $volume | get-eqlschedule
     if ($schedules.volumename -ne $null)
      {
     $sched_report = $schedules | SELECT volumename,schedulename,  
schedulestatus, scheduletype, startdate, starttime, enddate, endtime,  
repeatfactor, timefrequency, keepcount, accesstype, onlinestatus,  
replicationsite
     $sched += $sched_report
     }
 
 }

 

You can download the script here, it is as a .doc file to allow me to upload it on wordpress.com! so please rename as a .ps1 file. I will host it in an alternative location soon.

vSphere_Pro

Train Signal  the video training company have added a new title to their catalogue today the VMware vSphere Pro Series Training Vol 1. Aimed at vSphere admins to help improve you skill set, Volume 1 includes VMware View, ThinApp, Nexus 1000v and PowerCLI. With Virtual Desktops being on many companies to do list this year it is a must for anyone looking to be ahead of the game and know their way around VMware View. Also for me anything new I can learn with PowerCLI that will help me save time is a bonus.

The training is presented by Train Signals own David Davis, Hal Rottenberg the author of “Managing VMware Infrastructure with PowerShell” and VCDX Rick Scherer.

david_davis hal_rottenberg_headshot rick_scherer_headshot

For anyone who is not familiar with Train Signal I highly recommend you check out some of their free videos like this ThinApp one here >> http://www.trainsignaltraining.com/virtualize-applications-with-vmware-thinapp/2010-02-09/

Also if vSphere is new to you I can highly recommend the vSphere training >> VMware vSphere Training

I have ordered my copy of the vSphere Pro Training and will let you all know what I think when I receive my copy.

For full details visit the product page here >> http://www.trainsignal.com/VMware-vSphere-Pro-Series-Training-Vol-1-P91.aspx?utm_source=Site%2BPromo&utm_medium=Homepage%2BBanner&utm_campaign=vSphere%2BPro%2BLaunch

vsphere_pro_series_vol1_hero_tshirt

Update: Wow my script got a mention on the PowerScripting podcast 🙂 Episode 101 – Matthew Giles from Connect-SMART « PowerScripting Podcast

After doing lots of work with VMware View recently I have decided to try and write a few Powershell scripts to assist with View rollouts / administration. This first small script will update a custom field for each VM with the current logged in user. This helps considerably when your are in the vSphere client with a large amount of VM’s and need to track down the user of a particular VM. Maybe you need to log in to check an issue their having, investigate high CPU usage or just quickly find out which VM is assigned to which users. Obviously this can be done through the View Manager but most people won’t have this open on a daily bases.

001
002
003
004
005
006
connect-viserver yourvc
$vms = get-vm *xp*
ForEach($vm in $vms) 
{$QueryString = Gwmi Win32_ComputerSystem -Comp $vm 
$QueryString = $QueryString.userName 
if ($QueryString -eq $null) {$vm | Set-CustomField -Name “Logged in User” -Value "No One Logged In"} ELSE  {$vm | Set-CustomField -Name “Logged in User” -Value $QueryString}}

 

The script can either be ran as needed or scheduled to run using Windows Scheduled Tasks, for information on how to do this check out Alan Renouf’s blog post http://www.virtu-al.net/2009/07/10/running-a-powercli-scheduled-task/

As the script uses WMI to get the information regarding the logged in users, you must ensure you run this as user with sufficient privileges over the machines you are querying.

I am using a wild card in the get-vm command to find all my VM’s that contain xp in the name, this can easily be changed to meet the requirements of your View environment.

If no one is logged in when the script runs the custom field is updated with “No One Logged In”

As ever this is a work in progress and I am sure their are numerous ways it could be improved so I look forward to your suggestions and comments.

Example of how it looks in a list

image

Single VM View

image

As ever many thanks to Alan Renouf and his blog www.virtu-al.net for the inspiration.

Update

I have mixed success with this script, sometimes I am getting the logged in user returned correctly other time not. Would be interested to head what anyone else’s experiences. It seems the logged in user isn’t always returned from WMI, this seems strange considering I am using a domain admins account.

Are you like me and always end up with hundreds of Windows open then struggle to find the important ones to manage your infrastructure. This gets particularly difficult with the increasing amount of web management applications for your virtual infrastructure.

In comes Alan Renouf with another handy powershell script to create local vSphere plugins. This means you can access all you web management applications from inside the vSphere client.

You simply run the script which starts a handy form for you to fill in to create your plugin. Once you click create plugin the plugin is created and registered for you, all that is left for you to do it restart you vSphere client.

image

I have already used this to create a number of plugin’s to centralise all my VI management. A few can be seen below. To grab the code head over to Alan’s site www.virtu-al.net (http://www.virtu-al.net/2009/12/08/local-plugin-creator/) also if you find it useful and it saves you time consider donating a small amount to Alan’s test environment so he can keep producing these wonderful scripts. http://www.virtu-al.net/likemyscripts/ 

Veeam Enterprise Manager Plugin

veeam plugin

vFoglight Plugin

vfoglight plugin 2

View 4 Plugin

viewpluggin

SAN Management Plugin

SAN Management

Whilst I am currently learning about Powershell and writing a few scripts I thought I would blog my scripts here. Mainly for my benefit so I can easily find them and maybe some will be of use to someone out there. Also if you look at any of my scripts and cringe that something isn’t right or could be done better please let me know.

First a bit of a disclaimer, I find it easiest to learn by starting out with a script that I know that works and changing it to suit what I am doing. As such a number of my scripts may contain elements that are not my own work.  I will try and credit all third parties where possible, if I have missed you and I am clearly using your code please let me know and I will be happy to credit you.

Finally please remember I am a beginner so before using any scripts please test on a test system first.

The script below will create a very simple HTML Hostname and IP list at c:\IPReport.html which maybe useful when documenting a system. Elements of this script particularly the connection to the VIServer come from scripts found on Alan Renouf’s site www.virtu-al.net I highly recommend his site if you are learning powershell or just looking for scripts to help you with your daily admin tasks.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
param( [string] $VIServer )
#Check for VIServer name and give a friendly error
if ($VIServer -eq ""){
Write-Host
Write-Host "Please specify a vCenter Server name eg…."
Write-Host " powershell.exe VMGuestIPReport.ps1 MYVISERVER "
Write-Host
Write-Host
exit
}
#HTML header for output file
$head = ‘<style> BODY{font-family:Verdana; background-color:white;} TABLE{border-width: 1px;border-style: groove;border-color: black;border-collapse: collapse;} TH{font-size:0.8em; border-width: 1px;padding: 2px;border-style: groove;border-color: black;background-color:darkgrey} TD{font-size:0.8sem; border-width: 1px;padding: 2px;border-style: groove;border-color: black;background-color:lightgrey}</style>’

#Connect to vCenter

Write-Host "Connecting to VI Server"
Connect-VIServer $VIServer

# Get VM Name and IP Addressess

$header = "<H3>VM Guest – IP Report</H3>"
Get-VM | select name, @{ Name = "IP Addresses"; Expression = { $_.Guest.IPAddress }} | Sort-Object name | convertto-html -head $head | out-file c:\IPReport.html

Example output

image

As I have mentioned numerous times I am a big fan of The VESI and Alan Renouf’s powershell blog, well now Alan has released his powerpack for The VESI which means every VMware admin can have the power of Alan Renouf in their toolkit. Alan has taken his scripts and incorporated them in the VESI powerpack which means they can now be ran simply through the VESI GUI, saving you even more time. Due to current work commitments I haven’t had a lot of time to have a play with the powerpack yet but from the little I have seen it’s fantastic!

image

More information on The VESI can be found here

http://www.thevesi.org

and Alan’s powerpack can be found here

http://www.virtu-al.net/2009/11/02/virtu-al-vesi-powergui-powerpack/

If you like what you see and it starts saving you time consider a donation to Alan’s home test environment that will help us all in the long run!

http://www.virtu-al.net/likemyscripts/

OK all I seem to go on about at the moment is Virtualization Eco Shell and powershell, being a bit of a newbie to Powershell I have been amazed by just what I can do with it and have been eager to learn more. Whilst I have been learning and modifying code I have found on the internet, I have also started using Virtualization Eco Shell since its release.

The Virtualization Eco Shell is now the first tool I open when I get to site, I find it quicker and easier to get the information I need about an enviroment than using the VI / vSphere client.

A few examples of how I have recently used it

Reporting number of CPU’s and RAM in all the VM’s in an enviroment, using the advanced reporting pack that can be downloaded here >> http://thevesi.org/downloads.jspa within seconds I was able to produce a customised report similar to that below for a system with well over a hundred VM’s.

vmsummary2

Upon discovering a large amount of VMs we not time syncing with the host through VMware tools you would usually have to change the setting on each guest. After posting a question on the www.thevesi.org forum Scott has now added this functionality to the Virtualization Eco Shell >> http://thevesi.org/message.jspa?messageID=29595#29595

I am now able to set all my VM’s to sync at the click of a button

synctimewithhost

As for the vDiagrams they are fantastic, having previously used Veeam reporter to draw diagrams for infrastructures the vDiagrams option does it miles better and for free. Although I haven’t used the latest version of Veeams Reporter so this may have improved significantly. I just want the option to be able to diagram my network now as well! Maybe thats asking a bit much for a free product.

vmdiagram

For the latest information keep an eye on www.thevesi.org and also be sure to check out their blog here >> http://blog.thevesi.org/

Taken from here >> http://communities.vmware.com/message/1005498

Connect-VIServer cw-vc
Get-VM | % { Get-View $_.ID} | `
% {
$spec = new-object VMware.Vim.VirtualMachineConfigSpec
$spec.tools = New-Object VMware.Vim.ToolsConfigInfo
$spec.tools.syncTimeWithHost = $true
Get-View($_.ReconfigVM_Task($spec))
}