A. Mikkelsen

VMware ESX scripts, commands, tools and other nice to know things that will make your virtualization days easier!!!!

Yesterday I was supposed to receive last months billing reports from our vCloud Director environment.
But for some reason this didn’t happen :-(

I tried to logon to the VCCB web front end, but that wasn’t possible – the page just timed out.
Then I checked the VCCB  services and all was running.
Just to be sure I rebooted the server, with no luck.

Then I started to be scared…..

I checked the database login credentials, and the were correct.
So what happend?

After a quick google  I found a community thread about changing the IP for the back end database, and from this I located the config files containing the database connection information.

  1. Installation_Directory\apache-tomcat-6.0.18\webapps\vCenter-CB\WEB-INF\classes\hibernate.cfg.xml
  2. Installation_Directory\DataCollector-Embedded\classes\hibernate.cfg.xml

Locate the line

<property name="connection.url">jdbc:sqlserver://10.0.0.100;databaseName=vcenter_chargeback;integratedSecurity=false</property>

Here you can change the connection string as you see fit.
The connection string is based on Microsoft JDBC, so you are able to change it to fit you needs, choosing from all JDBC parameters. http://support.microsoft.com/kb/313100

I solved my problem by adding the port number of the MSSQL server to the connection string.

10.0.0.100:14331

I also found that you need to update 2 other config files.

  1. Installation_Directory\Config.xml
  2. Installation_Directory\DataCollector-Embedded\Config.xml

Locate the line

<hostport>10.0.0.100</hostport>

Here you just need to update the IP and/or port number.
I needed to add the portnumber.

<hostport>10.0.0.100:14331</hostport>

As you can see in the config.xml you are also able to change other parameters like

  • Databasename
  • username
  • Password
    This is encrypted so you need to update this through the supplied VCCB tool.
    Start -> All Programs -> VMware -> VMware vCenter Chargeback -> vCenter Chargeback Tools -> Update vCenter Chargeback Database Credentials

When you have updated all 4 configuration files, restart all services or restart the server.

Wait a few minutes and then login to the VCCB web front end….

All is now working :-)

In April VMware released their hardening guide for vSphere 4.1 (http://communities.vmware.com/docs/DOC-15413) , now the have also released a free tool to check your vSphere installations against their hardening guidelines.

The tool is called “VMware Compliance Checker for vSphere” – http://www.vmware.com/products/datacenter-virtualization/vsphere-compliance-checker/overview.html

If you haven’t read or read about the must have PowerCLI book “VMware vSphere PowerCLI Reference: Automating vSphere Administration“, by Luc Dekens, Alan Renouf, Glen Sizemore, Arnim van Lieshout and Jonathan Medd, then you need to check it out.

The book will show you how to automate your VMware infrastructure from vCenter to VM’s.

  • Automate installations
  • Create and configure VM’s
  • Secure your environment
  • Create reports

and much more.

Read a few chaphers from the book or buy the book (like I did :-) ) at:
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470890797,miniSiteCd-SYBEX,descCd-description.html

Download the PowerCLI examples from each chapter:
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470890797,miniSiteCd-SYBEX,descCd-DOWNLOAD.html

If you have your hosts connected to a Cisco network infrastructure, you can see a hosts CDP information directly from within the VI Client.

As you can see in the exampels below it’s quite impossible to get the full CDP picture if you have many hosts with multiple NICs.
So I created a script that retrieves all CDP info from all your hosts (even across multiple vCenters) and displays it as a webpage.
Now it’s possible to search and share the information :-)

The script is build up by a few functions

  • Retrieve the vCenter servers to retrieve host from.
    $objvCenterServer = Import-Csv -Path $strvCenterFilePath -Delimiter ";" | sort vCenter
    foreach($strvCenterServer in $objvCenterServer){
    # Check if VC is uncommented
    if ((!($strvCenterServer.vCenter.Contains("#"))) -and ($strvCenterServer.vCenter.Length -gt 0)){
    # Connect to vCenter Server
     Connect-VIServer -Server $strvCenterServer.vCenter -User $strvCenterServer.UserName -Password $strvCenterPWD
    
    # Add logic
    
    # Disconnect from vCenter server
    DisConnect-VIServer -Confirm:$false
    }}
    
  • Retrieve hosts from clusters.
    $arrDC = Get-Datacenter | Sort
    foreach($objDC in $arrDC){
     $arrCluster = Get-Cluster -Location $objDC | Sort
     # Only proceed if the Cluster isn't blank
     if ($($arrCluster | Measure-Object).count -gt 0){
     foreach($Cluster in $arrCluster){
     $vmhosts = Get-VMHost -Location $Cluster | Sort Name | Where-Object {$_.State -eq "Connected"} | Get-View
     #Only proceed if any hosts in cluster
     if ($vmhosts.Count -gt 0){
     foreach ($vmhost in $vmhosts){
    
    # Add logic for each host
    
    }}}}}
    
  • Retrieve hosts NICs CDP info.
    foreach ($vmhost in $vmhosts){
     $networkSystem = Get-view $vmhost.ConfigManager.NetworkSystem
    
     foreach($pnic in $networkSystem.NetworkConfig.Pnic | Sort Device){
     $pnicInfo = $networkSystem.QueryNetworkHint($pnic.Device)
    
     foreach($Hint in $pnicInfo){
    
     # LinkSpeed & MAC
     $record = 0
     $tmpSpeed = ""
     $tmpMAC = ""
     Do{
     If ($Hint.Device -eq $vmhost.Config.Network.Pnic[$record].Device){
     $tmpSpeed = $vmhost.Config.Network.Pnic[$record].LinkSpeed.SpeedMb
     $tmpMAC = $vmhost.Config.Network.Pnic[$record].Mac
     }
     $record ++
     }
     Until ($record -eq ($vmhost.Config.Network.Pnic.Length))
    
     # Duplex
     $tmpDuplex = ""
     if($Hint.ConnectedSwitchPort.FullDuplex -eq $true){
     $tmpDuplex = "Full"
     }
     if($Hint.ConnectedSwitchPort.FullDuplex -eq $false){
     $tmpDuplex = "Half"
     }
    
     # Status
     $tmpStatus = ""
     If (($tmpSpeed -ge 1000) -and ($tmpDuplex -eq "Full")){
     $tmpStatus = "OK"
     }else{
     If (($tmpSpeed -gt 0) -and ($tmpDuplex -eq "")){
     $tmpStatus = "CDP not working"
     }
     elseif (($tmpSpeed -gt 0) -and ($tmpDuplex -eq "Half")){
     if ($tmpStatus -ne ""){$tmpStatus += " / "}
     $tmpStatus = "Duplex config error"
     }
     elseif (($tmpSpeed -gt 0) -and ($tmpSpeed -lt 1000)){
     if ($tmpStatus -ne ""){$tmpStatus += " / "}
     $tmpStatus = "Speed config error"
     }
     else{
     $tmpStatus = "Link Down"
     }}}}
    
  • Seperate information included/excluded.
    $isExcluded = func_exclude_from_list -ExcludeHost $vmhost.Name -ExcludeVMNIC $Hint.Device -FromObj $objExcludeList
    
  • Generate html outputfile.
    Add-Content -Path $($strOutputPath + $strOutputFileName + ".TMP") -Value $strHTML
    if(Test-Path -Path $($strOutputPath + $strOutputFileName + ".htm")){
     Copy-Item -Path $($strOutputPath + $strOutputFileName + ".htm") -Destination $($strOutputPath + $strOutputFileName + $(Get-Date -uformat "%Y%m%d") + ".htm") -Force
    }
    Copy-Item -Path $($strOutputPath + $strOutputFileName + ".TMP") -Destination $($strOutputPath + $strOutputFileName + ".htm") -Force
    Remove-Item -Path $($strOutputPath + $strOutputFileName + ".TMP") -Force
    

vCenter servers are added/removed from the file “_All_vCenter_Hosts_.csv” .
A hosts NICs are moved to the exclude section, by adding it to the host exclude list “host_CDP_exclude.csv”.

The CDP information is sorted and saved in a HTML output file. If the script has been run before and an older version of the output file exist, it’s renamed and the new is saved (This supply you with a sort of history).

Get all script files here.
_All_vCenter_Hosts_.csv
host_CDP_exclude.csv
host_cdp_info_v01.ps1

————————-

For CDP information to be visible  in the VI client, CDP must also be enabled/configured on your physical Cisco switch – see example.
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1003885

To enable/change the CDP information on a host you have several options.

  1. If you are using dvSwitches in vSphere 4.x you can enable it from GUI .

    • Connect to vCenter using VI Client
    • From Home click Networking
    • Right click your dvSwitch and select Edit Settings
    • Under the Properties tab select Advanced
    • Check Cisco Discovery Protocol
    • Set Operation to Both
    • Click OK
  2. Using ESX Command line
    http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1003885
    (exchange vSwitch1 with the name of your vSwitch)

    • Show current setting
      esxcfg-vswitch -b vSwitch1
    • Set the new status (down, listen, advertise, both)
      esxcfg-vswitch -B both vSwitch1
    • Verify new settings
      esxcfg-vswitch -b vSwitch1
  3. Using vMA
    http://spininfo.homelinux.com/news/vSphere_PowerCLI/2010/03/24/Enable_CDP_on_vSwitch_on_all_hosts

     vicfg-vswitch --server <vcenter.domain.com> -h <esxi.domain.com> -B both <vSwitch1>

To view your CDP info you also a few options
See all options here:
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1007069

  1. GUI

    • Connect to vCenter or ESX using VI Client
    • Select a ESX host
    • Click the Configuration tab
    • Select Networking
    • Click the Info icon to the right of the vSwitch
    • A tool tip opens with CDP information for the selected physical network interface
  2. PowerShell
     Get-VMHost | Where-Object {$_.State -eq "Connected"} |
     %{Get-View $_.ID} |
     %{$esxname = $_.Name; Get-View $_.ConfigManager.NetworkSystem} |
     %{ foreach($physnic in $_.NetworkInfo.Pnic){
        $pnicInfo = $_.QueryNetworkHint($physnic.Device)
        foreach($hint in $pnicInfo){
           Write-Host $esxname $physnic.Device
           if( $hint.ConnectedSwitchPort ) {
              $hint.ConnectedSwitchPort
           }
           else {
              Write-Host "No CDP information available."; Write-Host
           }
        }
     }
    

See the full keynote from EMC Worls 2011, staring Poul Maritz – VMware CEO

http://www.youtube.com/watch?v=Ac9jQZi_lz8&feature=youtu.be&goback=%252Egde_1800113_member_55803385

After I upgraded vSphere vCenter & Client to 4.1 258902, I been getting an error in the vSphere Client.

A internal error occured in the vSphere Client. Details: Object reference not set to an instant object.

The solution is provided by VMware.
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1033560

It’s just replacing a DLL file :-)

The error is only with version 4.1 258902 and not 4.1 Update 1.

Hey all,
Just to let you know that I haven’t forgotten about you, but the last 6 months has been hectic.

In October I changed job from Logica to NNIT.
The change has meant that I haven’t had much the time to blog. This is no excuse, but now I’m back J

Over the next weeks I’ll post some of the PowerShell scripts that I have created months ago. I hope you can use them.

A. Mikkelsen

Last year I was asked to reduce the time spend on installing and configuring our ESX hosts.  Because we weren’t using Enterprise Plus licenses, we didn’t have Host Profiles.
I came up with a simple two-step process based on the EDA appliance and a custom PowerShell script.

  • Install the host from PXE.
    Only setting the minimum configuration, so it’s as versatile as possible.

    • Disk layout
    • Network teaming
    • FQDN and IP
  • Configure the host using a custom PowerShell script.
    Based on the Datacenter and Cluster the host is to be added to.

    • Add to vCenter
    • Set COS memory
    • Enable VMotion
    • License host
    • And much more…

A lot of blog posts are available on the net, on how to setup and install an ESX host using the EDA appliance so I won’t trouble you with this.

The PowerShell script is divided into several sections, I won’t explain everyone, only the most relevant, the rest is documented in the full script.
All steps in the script are logged to a host specific log file.

  • User input – Only 3 things are asked for when running the script, the rest is stored in the scripts Static section.
    • FQDN of the host (must be configured in DNS to work)
    • The environment – what environment is the host to be placed in, like PROD, DMZ, etc.
    • The hosts VMotion IP.
  • Add the host to the right cluster.
    You must have get the Datacenter/Cluster variable prior to adding the host, else it will just be placed in the first datacenter (See script for more info).

     add-vmhost $strHost -location $strvCenterDatacenter -user $strHostUser -password $strHostUserPWD -force: $true
     
  • Set the host in maintenance mode
     Get-VMHost -Name $strHost | Set-VMHost -State maintenance
     
  • License host.
    As you can see below, you have to supply the full name of the license you are adding, not just the license key.

     $targethostMoRef = (get-VMHost $strHost | get-view).MoRef
     $si = Get-View ServiceInstance
     $LicManRef=$si.Content.LicenseManager
     $LicManView=Get-View $LicManRef
     $licassman = (Get-View $LicManView.LicenseAssignmentManager)
    
     #$licassman.UpdateAssignedLicense($targethostMoRef.value,”YOUR LIC KEY”,”vSphere4 Enterprise Plus (1-12 cores per CPU”)
     $licassman.UpdateAssignedLicense($targethostMoRef.value,”YOUR LIC KEY”,”vSphere4 Enterprise (1-6 cores per CPU”)
     
  • Set the correct time zone.
     $strTimeZone = "Europe/Copenhagen"
     $tmpHost = Get-VMHost $strHost | get-view
     $tmpDTSystem =  $tmpHost.ConfigManager.DateTimeSystem
     $tmpMoRef = Get-View  $tmpDTSystem
     $tmpDateConfig = New-Object      Vmware.Vim.HostDateTimeConfig
     $tmpDateConfig.timeZone = $strTimeZone
     $tmpMoRef.updateDateTimeConfig($tmpDateConfig)
     
  • Add NTP servers.
    Use an array of NTP servers like
    $arrNTPServer = @(“dk.pool.ntp.org”,”de.pool.ntp.org”,”us.pool.ntp.org”,”clock.cimat.ues.edu.sv”,”ntp1.gbg.netnod.se”,”ntp1.theremailer.net”)

     Add-VMHostNtpServer -VMHost $strHost -NtpServer $arrNTPServer -Confirm:$false
     

    If you want you can restart the NTP service – only do it if you don’t plan on restarting the host after configuring.

     Restart-VMHostService $ntpd -Confirm:$false
     
  • Open firewall rules
    I always open the following firewall rules so that NTP and the SSH is working

     Get-VmhostFirewallException -VMHost $strHost -Name "NTP Client" | Set-VMHostFirewallException -enabled:$true
     Get-VmhostFirewallException -VMHost $strHost -Name "SSH Client" | Set-VMHostFirewallException -enabled:$true
     [/powershel]</li>
    	<li>Set the correct DNS servers
     Use an array of DNS servers, this way you can add multiple DNS servers at      once.
     @("10.10.10.40","10.10.10.30") or @("10.10.10.40")
     [powershell]
     $strHost = @("10.10.10.40","10.10.10.30")
     Get-VMHost -Name $strHost | Get-View | %{$tmpNS = Get-View -Id $_.configManager.networkSystem
     $tmpDNS = $tmpNS.NetworkConfig.DnsConfig
     $tmpDNS.domainName = $strHostDomain
     $tmpDNS.address = $arrDNSsrv
     $tmpDNS.searchDomain = $strSearchDomain
     $tmpNS.updateDnsConfig($tmpDNS)}
     
  • Configuring network, adding network including VMotion.
    See the script for the full script.

     $vSwitch = Get-VirtualSwitch $strHost -Name vSwitch0
     #Set-VirtualSwitch -VirtualSwitch $vSwitch -Nic vmnic1
     New-VirtualPortGroup -VirtualSwitch $vSwitch -Name "VMOTION" -VLanId 0
     New-VMHostNetworkAdapter -VMHost $strHost -PortGroup "VMOTION" -VirtualSwitch $vSwitch -IP $strVMotion -SubnetMask $strSubnetMask -VMotionEnabled $true
     $strNetConfig = Get-View (Get-VMHost $strHost | Get-View).ConfigManager.NetworkSystem
     $strIPRoute = New-Object VMware.Vim.HostIpRouteConfig
     $strIPRoute.defaultGateway = $strGateway
     $strNetConfig.UpdateIpRouteConfig($strIPRoute)
     New-VirtualPortGroup -VirtualSwitch $vSwitch -Name "PROD" -VLanId 200
     New-VirtualPortGroup -VirtualSwitch $vSwitch -Name "PXE" -VLanId 0
     

    If needed you can remove the default VM network

     $vSwitch = Get-VirtualSwitch $strHost -Name vSwitch0
     $vmnetwork = Get-VirtualPortGroup -VirtualSwitch $vSwitch -Name "VM Network"
     Remove-VirtualPortGroup -VirtualPortGroup $vmnetwork -Confirm:$false}
     
  • Reboot the host J
     Get-VMHost -Name $strHost | %{Get-View $_.ID} | %{$_.RebootHost_Task($TRUE)}
     
  • If you want your script to wait for the host to be rebooted before continuing, you can do it with these two loops.
     do{
     $result = Get-VMHost $strHost
     Start-Sleep 10 # Wait 10 sec
     }
     Until($result.State -ne "Maintenance")
     # Maintenance - because host entered Maintenence mode earlier
    
     do{
     $result =  Get-VMHost $strHost
     Start-Sleep 10 # Wait 10 sec
     }
     Until($result.State -eq "Maintenance")
     
  • Finally exit the host from maintenance mode.
     Get-VMHost -Name $strHost | Set-VMHost -State connected
     

If everything is configured correctly, DRS should start migrating VM’s to the newly added host.

This script helped reducing the time spend on installing and configuring a host from 90 minutes to about 18 minutes. That’s a reduction of more than 500%, time you can use on other cool PowerShell tasks. J

By using a script to customize our hosts, we also gained two other benefits.

  1. Compliance – a host is always installed and configured the exact same way each time.
  2. Each step is documented in a host specific log file.

The full script can be downloaded here.



Some time ago I was asked to create a script that could list each VM’s videocard settings.

$VMs = Get-View -ViewType VirtualMachine | sort Name
foreach($VM in $VMs){
	write "$($VM.Name) $($VM.Guest.Screen.Width)/$($VM.Guest.Screen.Height)"
}

As you could see that was quite simple.
I using the Get-View -ViewType to speed up the query – See LucD’s post on http://communities.vmware.com/message/1511671#1511671 for more info.

Then I was asked to set all VM’s videocard setting to Auto Detect (Default setting).

$vms = Get-View -ViewType VirtualMachine | sort Name
foreach ($vm in $vms){
	if ($vm.Runtime.PowerState -eq "PoweredOff") {
		if ($vm.Config.Version -eq "vmx-07"){
			foreach($dev in $vm.Config.Hardware.Device){
				if ($dev.DeviceInfo.Label -like "Video*"){
					if ($dev.UseAutoDetect -match "False" ) {
						$VMName = $vm.Name
						$VMcidcrd = New-Object VMware.Vim.VirtualMachineVideoCard
						$VMcidcrd.UseAutoDetect = 1
						$VMcidcrd.Key = 500
						$spec = new-object VMware.Vim.VirtualDeviceConfigSpec
						$spec.Device = $VMcidcrd
						$spec.Operation = "edit"
						$VMSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
						$VMSpec.DeviceChange = $spec
						$vm.ReconfigVM_Task($VMSpec)
						write "$($vm.Name) - Video Settings Changed"

					}
				}
			}
		}
	}
}

As you can see this requires a bit more.
The VM has to be
• Powered Off
• Running vHW version 7
Download the full script here.

If you want to set the videocard setting to a specific MB, then just change the line from the above script

$VMcidcrd.UseAutoDetect = 0

To

$VMcidcrd.UseAutoDetect = 0

And add the line

$VMcidcrd.VideoRamSizeInKB = 131072

Where the 131072 us the amount of MB you want multiplied with 1024
Ex. 128 x 1024 = 131072

September 15, 2010 VMware released version 2.0 of its Project Onya Alpha.

You can download and read more about Project Onyx on the projects home page.
http://communities.vmware.com/community/vmtn/vsphere/automationtools/onyx?view=overview

This project is a must have for all PowerCLI geeks :-)

When you upgrade your vSphere environment you normally also upgrade the VM’s virtual hardware to version 7, to take advantage of the new features. This is pretty normal procedure for all VMware admins.

But in some very very rare cases you might need to move a VM upgraded to hardware version 7, to a host that doesn’t support VM’s running hardware version 7.
From a host running ESX 4.x to a host running ESX 3.x

So what to do.
There is two ways you can accomplice this task.

The first way is to use the free VMware Converter tool.
Some great guides have been created by others so I don’t want to do it all over again.
The only thing is that it can take some time to convert the VM, but it is a proven and stable method.
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1028019
Or
http://www.techhead.co.uk/vmware-esx-how-to-downgrade-a-vms-vm-versionhw-level-from-7-4-0-to-4-3-x
Or
http://blog.vmpros.nl/2010/04/09/vmware-how-to-downgrade-vm-hardware-level-7-to-4/

The other way is to do it manually, this way is a lot faster, but there is a risk that it will corrupt the VM, so make sure you have a working backup.
Use this guide on your own risk

  • Powered off the VM
  • Make sure the VM doesn’t have any snapshots before proceeding
  • From the ESX console or from a Putty session, edit the VMs VMX file, using your favorite editor
    vi /vmfs/volume/DS1/WIN2008-001/WIN2008-001.vmx
  • Change the virtual hardware version from:
    virtualHW.version = “7”

    To

    virtualHW.version = “4”
  • You don’t need to change config.version = “8”, since ESX 3.x already uses this version
  • Change the virtual controller, because virtual hardware version 4 doesn’t understand the version 7 virtual controller, from:
    scsi0.virtualDev = “lsisas1068”

    To

    scsi0.virtualDev = “lsilogic”
  • From the ESX console or from a Putty session, edit the VMs VMDK pointer file/files (if more than one virtual disk), using your favorite editor
    vi /vmfs/volume/DS1/WIN2008-001/WIN2008-001.vmdk
  • Change the virtual hardware version from:
    ddb.virtualHWVersion = "7"

    To

    ddb.virtualHWVersion = "4"
  • You should now be able to power on the VM as virtual hardware version 4.

Using IBM Blades and Cisco switches to run your ESX enviroment?

If yes, have you tested what happens if you unplug the network cables going into one switch?

If you like me have bundled 2 or more cables going from one switch, to one backbone switch and done the same for the other switch, then your VM’s using that switch will loose network connection (from outside the host).
This is not the way I wanted the setup to work.

After a bit of googling i found a blog from Scott Lowe (http://blog.scottlowe.org/2007/06/22/link-state-tracking-in-blade-deployments/) about the problem and also a solution.
The solution is called Link State Tracking. Many users have tried the solution and have got it to work, so I had to test it…..

I added the following lines to each of the Blade Switches (Port-Channel, group and interfaces may be different on your system).

----------UPLINK to CORE switch------------
interface Port-Channel1
link state group 1 upstream

----------LINK to Blade server------------
interface range GigabitEthernet0/1 - 14
link state group 1 downstream

----------Global command------------
link state track 1

conf t
interface Port-Channel1
link state group 1 upstream
interface range GigabitEthernet0/1 - 14
link state group 1 downstream
link state track 1

Remember to write the changes to memory using

wri

After this was done on both Blade switches, i just had to test it.
I started a ping to a VM that I knew was using Switch1 to communicate with external network traffic.
Then I unplugged the to 2 network cables going into Switch1 and waited to see if the ping command would loose the communication with the VM….
It didn’t loose connection. So the the VM must have switched to Switch2.

So configuring the Blade Switches for Link State Tracking is to proper way to configure the switches.
A big thanks goes to Scott Lowe for the blog on Link State Tracking.

After we upgraded to vSphere 4.1, the SCSI adaptor of all our WINXP guests changed from LSI Logic Parallel  to BusLogic Parallel. This change should normally not create any warnings or problems it VMware Tools are up to date.

But after the upgrade all our WINXP guests got the following warning when powered on in the event log.

Message from esxhost01.labt.local: The guest operating system is Windows XP and you have one or more virtual SCSI devices installed in your virtual machine. Windows XP does not support the BusLogic SCSI adapter that VMware ESX currently uses for its virtual SCSI devices. Select OK to continue or Cancel to cancel. info 22-09-2010 15:55:25 VM name vpxuser
I then changed the SCSI adaptor back to LSI Logic Parallel and I now got almost the same warning.

Message from esxhost01.labt.local: The guest operating system is Windows XP and you have one or more virtual SCSI devices installed in your virtual machine. Windows XP does not support the LSI Logic SCSI adapter that VMware ESX currently uses for its virtual SCSI devices. Select OK to continue or Cancel to cancel. info 22-09-2010 15:55:25 VM name vpxuser

I contacted VMware support and they told me that it was a known “feature”/”bug” and send me the following link to suppress the waring in the Event log.
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1007122

There is two ways to suppress the warning.

Through vSphere Client

  • Using the vSpher Client logon to your vCenter server.
  • Poweroff the VM.
  • Edit the VM’s settings
  • Navigate to Options > Advanced > General
  • Click Configuration Parameters
  • Add the following rows, by using Add Row
    • If you have a BusLogic Parallel SCSI adaptor
      buslogic.noDriver = "FALSE"
    • If you have a LSI Logic Parallel SCSI adaptor
    • lsilogic.noDriver = "FALSE"
  • Click OK twice to close the dialogs and save the changes.
  • PowerOn the VM

Editing the VMX file

  • Open a SSH to the host ex. using Putty
  • Navigate to the VM’s files (relpace with your own path)
    cd /vmfs/volumes/lun01/winxp01/
  • Open the config file  in your favorit editor .
    vi winxp01.vmx
  • Add the following line to the file
    • If you have a BusLogic Parallel SCSI adaptor
    • buslogic.noDriver = "FALSE"
    • If you have a LSI Logic Parallel SCSI adaptor
    • lsilogic.noDriver = "FALSE"
  • Save and close the config file.
  • PowerOn the VM

I haven’t tested if it possible to add the lines to the global config file on each host (/etc/vmware/config) for all VM’s..

I will test this next week.

After we upgraded to vSphere 4.1 we have been expirence problems with VM’s entering FullScreen mode.

The issue is that 9/10 times a VM enter FullScreen mode, you are not able to move the mouse to the bottom part of the screen and select a program or the Start option.

VMware is aware of the bug.
They say that it is resolved  in ESX 5 (next year)  – FullScreen mode should be completely redesigned.

Until then a patch is requested from PR, but no timeframe is released.
So if you have the same problem, please file a support request with VMware to speed up the process.

Yesterday we upgraded one of our vSphere Clusters to 4.1 – it went smoothly :-)

But today the users reported that they weren’t able to use cut % paste between the guest and their computer using the vSphere Client (Console).

After a quick google we found that VMware has tightened the vSphere security by disabling this feature. See VMware KB 1026437.

If you need the cut & paste functionality you can enable it again on the guest or host level.

For a single VM:

  • Using the vSpher Client logon to your vCenter server.
  • Poweroff the VM.
  • Edit the VM’s settings
  • Navigate to Options > Advanced > General
  • Click Configuration Parameters
  • Add the following rows, by using Add Row
    isolation.tools.copy.disable –  false
    isolation.tools.paste.disable  – false
    
  • Click OK twice to close the dialogs and save the changes.
  • PowerOn the VM

For all VM’s on a host ESX/ESXi

Must be done on all hosts, so you don’t loose the functionality when the VM is migrated to another host.

  • Open a SSH to the host ex. using Putty
  • Open /etc/vmware/config in your favorit editor .
  • Add these lines to the file

    isolation.tools.copy.disable="FALSE"
    isolation.tools.paste.disable="FALSE"
    
  • Save and close the config file. Cut & Paste will work after a VM powerson, reboots or resume.

Friday I was at a customer to upgrade their ESXi 4.0 (free) to version 4.1.
This should have been an easy task, download CD, burn it and install.

This wasn’t the case, the new ESXi 4.1 wouldn’t install, it kept freezing during the extract of the cim.vgz file.
The problem occurred on both the Dell custom of ESXi 4.0 U1 and the standard ESXi 4.1.
We googled and googled but didn’t find a solution – in the end we blamed the error on the old bios version 1.1.4.

To my luck the customer still had the CD we installed the server with 9 months ago – ESXi 4.0.

We installed ESXi using the old CD and then everything was working – but we still needed to upgrade to ESXi 4.1.

So now what to do …….

Normally you use the hostupdate utility or the Remote CLI but the hostupdate utility is not included in the free version of ESXi and the we didn’t want to install the Remote CLI on the computer.
To my luck I had the hostupdate utility installed but i kept getting this error when trying to upgrade the ESXi host.

“Failed to read the upgrade package metadata.xml”

The solution to our problem was:

  1. Since it was a ESXi free with out support, we decided to use the “ESXi command line interface”, witch is unsupported.
    Follow this guide to enable it (http://www.bauer-power.net/2010/04/vmware-esxi-hack-to-allow-ssh.html).
  2. Download and extract the upgrade ZIP file from VMware.
  3. From the VIclient, upload the extracted files to the host datastore, using the “datastore browser”
    - I uploaded the files to a folder named “upgrade”
  4. Put the ESXi host in “Maintance Mode”
    - Since it is a ESXi, this can only be done when all VM’s are powered off.
  5. Connect the the ESXi console using ex. Putty.exe.
  6. Navigate to the upgrade directory.
    cd /vmfs/volumes/local-datastore/upgrade
  7. Begin the upgrade process
    esxupdate update -m metadata.zip
    
  8. When the upgrade is finished, reboot the host.
    reboot
  9. To verify the new build number:
    - Connect to the host using the VIclient
    - Select the host
    - Choose the “Summery” tab
    - Verify that the ESXi version number and build has been updated

Just released the complete powershell script to control vRanger backup from vCenter.

Read about the script and it’s features here.

Download it here.

If you ever have experienced that after your vCenter server reboots – due to Windows updates, the “VMware VirtualCenter Server” service is not starting?

I have seen it a few times and every time it’s during a weekend :-(

So to make sure your vCenter service (or other) is always running you could use this powershell script to check if a service is running, and if not start it.
To make sure you know if the service wasn’t started after a reboot or other cause, I have added a mail function to the script :-)

function FuncCheckService{
    param($ServiceName)
    $arrService = Get-Service -Name $ServiceName
    if ($arrService.Status -ne "Running"){
        Start-Service $ServiceName
        FuncMail -To "to-email@domain.com" -From "from-mail@domain.com"  -Subject "Servername : ($ServiceName) service started." -Body "Service $ServiceName started" -smtpServer "relay.mailserver.com"
    }
}

function FuncMail {
    #param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
    param($To, $From, $Subject, $Body, $smtpServer)
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = $From
    $msg.To.Add($To)
    $msg.Subject = $Subject
    $msg.IsBodyHtml = 1
    $msg.Body = $Body
    $smtp.Send($msg)
}

FuncCheckService -ServiceName "VMware VirtualCenter Server"

Create a PS1 file and schedule it to run every 15 or 30 minutes.

It works great and is simple….

If you want to configure a hosts NTP server list through PowerCLI you have a few cmdlet at your disposal.

  • Get-VMHostNtpServer
  • Remove-VMHostNtpServer
  • Add-VMHostNtpServer
  • Get-VMHostService
  • Set-VMHostService
  • Get-VmhostFirewallException
  • Restart-VMHostService

Get a list of NTP servers on a host.

Get-VMHostNtpServer -VMHost "esx01.lab.local"

To remove a specific NTP server from a host NTP server list.

Remove-VMHostNtpServer -VMHost "esx01.lab.local" -NtpServer '127.127.1.0' -Confirm:$false

To remove all NTP servers on a hosts NTP server list.

$arrNTPList = Get-VMHostNtpServer -VMHost "esx01.lab.local"
Remove-VMHostNtpServer -VMHost "esx01.lab.local" -NtpServer $arrNTPList -Confirm:$false

To add a single NTP server to a hosts NTP server list.

Add-VMHostNtpServer -VMHost "esx01.lab.local" -NtpServer "dk.pool.ntp.org" -Confirm:$false

To add a a list of NTP servers to a hosts NTP server list.

$arrNTPServers = ("dk.pool.ntp.org","de.pool.ntp.org","us.pool.ntp.org")
Add-VMHostNtpServer -VMHost "esx01.lab.local" -NtpServer $arrNTPServers -Confirm:$false

To set the NTP deamon (service) to start automatic.

Set-VMHostService -HostService (Get-VMHostservice -VMHost (Get-VMHost "esx01.lab.local") | Where-Object {$_.key -eq "ntpd"}) -Policy "Automatic"

Open firewall to allow the NTP deamon to communicate with the NTP server.

Get-VmhostFirewallException -VMHost "esx01.lab.local" -Name "NTP Client" | Set-VMHostFirewallException -enabled:$true

To restart the NTP deamon (service) after you have configured it – without restarting the host.

$ntpd = Get-VMHostService -VMHost "esx01.lab.local" | where {$_.Key -eq 'ntpd'}
Restart-VMHostService $ntpd -Confirm:$false

Since Vizioncore came out with vRanger 4.x, last year, I been working on porting the VBS script “vRanger Script version 2.0” to Powershell.
During this time I have found several bugs/missing functionality in the vAPI.
Vizioncore have corrected the bugs with new releases of vRanger.
The first vRanger version where all vAPI cmdlets worked in was version 4.2.3.

Porting the script from VBS presented me with a few challenges.

  • A reported error in the Get-Date cmdlet in Powershel 2.0.
    Had to use a workaround.

A few words on the scrips functionality.

  • Control vRanger backups from vCenter (simple – one interface).
  • Perform a FULL backup of DiskO of a VM.
  • Perform a FULL backup of all disks of a VM.
  • Backup a VM on a specific weekday.
  • Control what week (Even/Odd).
  • Create a log file.
  • Delete previous backup files from repository.
  • Delete previous savepoints.
  • Send an email when the jobs are completed – incl. succes/errors.
  • Offload the files to tape – TSM
  • Send mail when TSM is finished offloading backup files.
  • And many more…..

When I started coding the script, I found, that if I used functions for all functionality the script was easier to read. Using functions also supplied me with the opportunity of reusing functions – less work :-) .

Some of the functions was created using examples posted and mailed by Scott Harold from Quest and TheVesi./vEcoShell.

Prerequirements

The script can be downloaded here.

A quick overview of the functions.
Include the right PSSnapins

function LoadSnapin{
    Add-PSSnapin vRanger.API.PowerShell -ErrorAction SilentlyContinue
    Add-PSSnapin vmware.VimAutomation.core -ErrorAction SilentlyContinue
}

LoadSnapin

Delete all previous savepoints – from the repository.

function RemoveAllSavePoints{
	param ($RASP_RepoName)
	$RASP_repoID = Get-Repository | where {$_.Name -eq $RASP_RepoName}
	$RASP_SPlist = Get-RepositorySavePoint -ID $RASP_repoID.Id

	foreach ($RASP_SP in $RASP_SPlist){
		#write $RASP_SP
		Remove-SavePoint -SavePointsToRemove $RASP_SP
	}
}

RemoveAllSavePoints "Remote-Location"

Is a backup job exist with the same name as the one to create – delete it.

function Del-vRangerBackupJobs {
	param ($delJobName)
	$delTemplateID = Get-JobTemplate | where {$_.JobName -eq $delJobName}
	# Verify that a BackupJob named XXX is present before deleting it.
	if ($delTemplateID){
		#write $delTemplateID.JobName
		Remove-JobTemplate -id $delTemplateID.Id
	}
}

Del-vRangerBackupJobs "$Wednesday-Even"

Create the list of VMs to exclude.

function Filter-VMbyCF {
    param ($customF, $val)
    foreach ($vm in $vmlist) {
        $vm.CustomFields | ForEach-Object {
            $cf = $_
            if ($_.Key -like $customF -and $_.Value -like $val){
                    return $vm.name
            }
        }
    }
}

function New-vRangerExcludeList {
    param ($exclude, $include)
    $excludeArray = @()
    $exclude | ForEach-Object {
        if ($include -notcontains $_.Name){
            $excludeArray += ($_.Config.Uuid)
        }
    }
    return $excludeArray
}

$vmlist = Get-VM
$tmplist = Get-Template
$vmlist= $vmlist + $tmplist
$vmFilter = Filter-VMbyCF $customField $CFValue
$vmlistview = $vmlist | Get-View
$excludeList = New-vRangerExcludeList -exclude $vmlistview -include $vmFilter

Create the new backup job.

function New-vRangerBackupJob {
	param ($customJobName, $customCFValue, $customFieldName, $customRepoName, $customExcludeList, $customEmail)
        $jobDesc = "This backup job is created by Logica for use in DR.  All VMs with a Custom Field labeled: $customFieldName with a value of: $customCFValue will be backed up"
        $jobEntity = Get-InventoryEntity -Type VirtualCenter
	$jobRepos = Get-Repository | where {$_.Name -eq $customRepoName}
        $jobFlag = New-BackupFlag -CheckDestinationFreeSpace:$true -UseCompression:$true -PerformNetworkBackupOnFailure:$true

	# Check if all disks or just disk 0
	if ($customJobName -like "*-All*"){
		#write "All - Disks"
		#Add-BackupJobTemplate -JobName $customJobName -JobDescription $jobDesc -JobEntity $jobEntity -ExcludedVMList $customExcludeList -NotificationList $email -TargetRepository $jobRepos -Flags $jobFlag -NumberOfSavePoints 1 -SpaceSavingTechnologyTypeFlag None
		Add-BackupJobTemplate -JobName $customJobName -JobDescription $jobDesc -JobEntity $jobEntity -ExcludedVMList $customExcludeList -NotificationList $customEmail -TargetRepository $jobRepos -Flags $jobFlag -NumberOfSavePoints 1 -SpaceSavingTechnologyTypeFlag None -SpaceSavingCountThreshold 6 -SpaceSavingPercentSizeThreshold 50
	}
	else{
		#write "Only Disk 0"
		#Add-BackupJobTemplate -JobName $customJobName -JobDescription $jobDesc -JobEntity $jobEntity -ExcludedVMList $customExcludeList -NotificationList $email -IncludedDiskList 0 -TargetRepository $jobRepos -Flags $jobFlag -NumberOfSavePoints 1 -SpaceSavingTechnologyTypeFlag None
		Add-BackupJobTemplate -JobName $customJobName -JobDescription $jobDesc -JobEntity $jobEntity -ExcludedVMList $customExcludeList -NotificationList $customEmail -IncludedDiskList 0 -TargetRepository $jobRepos -Flags $jobFlag -NumberOfSavePoints 1 -SpaceSavingTechnologyTypeFlag None -SpaceSavingCountThreshold 6 -SpaceSavingPercentSizeThreshold 50
	}
}

New-vRangerBackupJob "Wednesday-Even" "Wednesday-Even" "Backup" "Remote-Location" $excludeList "to@email.com"

Start the backup job.

function Run-BackupJob{
	param ($runJobName)
	$runTemplateID = Get-TemplateID $runJobName
	Run-JobsNow $runTemplateID
}

Run-BackupJob "Wednesday-Even"

Wait for the backup job to finish.

function Get-TemplateID{
	param($tmpJobName)
	$arrTemplate = get-jobtemplate | where {$_.JobName -eq $tmpJobName}
	return $arrTemplate.ID
}

function WaitForJobToFinish{
	param ($strWaitJob)
	$strCompleted = "NotStarted"
        Start-Sleep -Seconds 300	# 5 minutes
	$jobTemplates = get-JobTemplate | where {$_.JobName -eq $strWaitJob}
	foreach ($job in $jobTemplates){
		do{
			$tasksinfo = get-job |where {$_.ParentJobTemplateID -eq $job.TemplateVersionID}
			foreach ($task in $tasksinfo){
				Start-Sleep -Seconds 300	# 5 minutes
				$strCompleted = $task.JobState

                # Make sure job is running - if not start it...
                if ($task.JobState -eq $NULL -or $task.JobState -eq "NotStarted"){
                    Run-BackupJob $strWaitJob
                    Start-Sleep -Seconds 120	# 2 minutes
                }
			}
		}
		while ($strCompleted -notmatch "Completed")
	}
}

WaitForJobToFinish "Wednesday-Even"

Send TSM finished mail.

function FuncMail {
	#param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
	param($To, $From, $Subject, $Body, $smtpServer)

	$msg = new-object Net.Mail.MailMessage
	$smtp = new-object Net.Mail.SmtpClient($smtpServer)
	$msg.From = $From
	$msg.To.Add($To)
	$msg.Subject = $Subject
	$msg.IsBodyHtml = 1
	$msg.Body = $Body
	$smtp.Send($msg)
}

FuncMail -To "to@email.com" -From "from@email.com" -Subject "vRanger Pro: TSM backup finished" -Body "Your Body" -smtpServer "your.mailserver.com"
Powered by WordPress Web Design by SRS Solutions © 2012 A. Mikkelsen Design by SRS Solutions