vCenter Cluster memory in use report

May 13th, 2010

I wanted a report for each cluster showing the total amount of memoy on the hosts, how much was provisioned to the VMs and how much wa sin use… so I came up with this little bit of code ths week..

$vchosts = @()
$vc = @()
$ReportOutput = @()
$ReportRegion = @()
$ReportPlatform = @()
$Decimals = 1
$CurrentDate = get-date -format "yyyyMMdd"
$YesterdayStart = (get-date -Hour 00 -Minute 00 -Second 00).adddays(-1)
$YesterdayEnd = (get-date -Hour 23 -Minute 55 -Second 00).adddays(-1)
$VIServ = 'vcenter.fqdn'
$Region = 'Region'
 
    $creds = New-Object System.Management.Automation.PsCredential(“DOMAIN\vCenterAccount”, (Get-Content “c:\mycred.crd” | ConvertTo-SecureString))
    $VIServer = Connect-VIServer -Server $VIServ -Credential $creds
 
$objMemory = @()
$clusters = Get-cluster
foreach ($cluster in $clusters) {
	Write-Host "Processing Cluster "$cluster.Name
	$objMem = "" | Select Region,Date,ClusterName,ClusterPhysMemoryMb,ClusterAllocatedMemoryMb,ClusterInUseMemoryMb,PercentAllocated,PercentInUse
	$objMem.Region = $Region
	$objMem.Date = $CurrentDate
	$objMem.ClusterName = $cluster.Name
	$objMem.ClusterPhysMemoryMb = 0
	$objMem.ClusterAllocatedMemoryMb = 0
	$objMem.ClusterInUseMemoryMb = 0
	$vmhosts = $cluster | Get-vmhost
	if ($null -ne $vmhosts) {
        foreach ($vmhost in $vmhosts) {
            $vmhostview = $vmhost | Get-View
			$objMem.ClusterPhysMemoryMb = [math]::round($objMem.ClusterPhysMemoryMb + $vmhostview.Hardware.MemorySize / 1Mb)
         	$objMem.ClusterInUseMemoryMB = [math]::round($objMem.ClusterInUseMemoryMb + $vmhostview.Summary.QuickStats.OverallMemoryUsage)
			$vmsonhost = $vmhost | Get-VM
			foreach ($vm in $vmsonhost) {
				$objMem.ClusterAllocatedMemoryMb = [math]::round($objMem.ClusterAllocatedMemoryMb + $vm.MemoryMB)
			}
        }
	$objMem.PercentAllocated = [math]::round($objMem.ClusterAllocatedMemoryMb / $objMem.ClusterPhysMemoryMb * 100)
	$objMem.PercentInUse = [math]::round($objMem.ClusterInUseMemoryMB / $objMem.ClusterPhysMemoryMb * 100)
	$objMemory = $objMemory + $objMem
	}
}
 
$Filename = "D:\vSphere\Reports\"+$CurrentDate+"_Cluster_Memory_Summary_Report.csv"
$objMemory | Sort ClusterName | Export-Csv $Filename -noType
$Filename = "D:\vSphere\Reports\Cluster_Memory_Summary_Report.csv"
$objMemory | Sort ClusterName | Export-Csv $Filename -noType 
 
(get-view serviceinstance).Client.Logout()

Use a credential file to not put password in PowerCLI script

April 9th, 2010

I started scripting, and put the password to conenct to the vcenter server in the scripts, i decided that wasnt such a good idea, even though im mainly using a read only account.  So i found some code that enables you to use a credential file.

Opern PowerCLI

Paste this code into the console

  1. Function Set-Cred ($File) {
  2. $Credential = Get-Credential
  3. $credential.Password | ConvertFrom-SecureString | Set-Content $File
  4. }

then in the console type

Set-Cred c:\mycred.crd

There will be a prompt for a userid and password, enter those details.

The credential file will be created.

Now you can use connect-viserver with the credential file.

  1. $creds = New-Object System.Management.Automation.PsCredential(“AD\ADUSER”, (Get-Content “c:\mycred.crd” | ConvertTo-SecureString))
  2. $VIServer = Connect-VIServer -Server $VIServ -Credential $creds

Summary CSV extracts of ESX Hosts and VM types for MI

April 8th, 2010

I have read only access to about 30 vCenter servers globally, I need to pull out details of Hosts VM totals and types so I can report on global usage…

Another script to do this, it reads the vCenter names from a txt file, connects with an AD account that has read-only access in each vCenter server and pulls out the inventory info i need for each vcenter server.

Then collates the info into multiple CSV files.

  1. # vCenter ESX Host and VM Summary Report
  2. # Connects to multiple vCenter Servers
  3. # Captures totals for ESX Hosts, and VMs and works out how many Windows, Linux and Solaris VMs there are
  4. # Saves this info into various CSV viles depending on how detaild a report you need
  5. # John Gibson
  6. #
  7.  
  8. $vchosts = @()
  9. $vc = @()
  10. $ReportOutput = @()
  11. $ReportRegion = @()
  12. $ReportPlatform = @()
  13. $AllVMs = @()
  14. $Decimals = 1
  15. $CurrentDate = get-date -format "yyyyMMdd"
  16. $YesterdayStart = (get-date -Hour 00 -Minute 00 -Second 00).adddays(-1)
  17. $YesterdayEnd = (get-date -Hour 23 -Minute 55 -Second 00).adddays(-1)
  18.  
  19. # Read a text file which contains a list of vCenter server names and their region name
  20. $file = "D:\Group_vCenter_Servers.txt"
  21. $vchosts = get-content $file
  22.  
  23. # For each vCenter Server
  24. foreach($vc in $vchosts){
  25. $vc1 = $vc.split("`t ")
  26. write-host "Processing Stats for "$vc
  27. $VIServ = $vc1[0]
  28. $Region = $vc1[1]
  29. $creds = New-Object System.Management.Automation.PsCredential(“AD\ADUSER”, (Get-Content “c:\mycred.crd” | ConvertTo-SecureString))
  30. $VIServer = Connect-VIServer -Server $VIServ -Credential $creds
  31.  
  32. if ($null -eq $VIServer) {
  33. write-host "Retrying Connect to "$VIServ
  34. $VIServer = Connect-VIServer -Server $VIServ -Credential $creds
  35. }
  36.  
  37. $ReportRegion = "" | Select Region,vCenterServer,ESXHosts,TotalVM,TotalWinSrv,Win2000,Win2003,Win2008,WinNT,WinXP,WinVista,Win7,RedHat,Suse,Solaris,Other
  38. $ReportRegion.Region = $Region
  39. $ReportRegion.vCenterServer = $VIServ
  40. $vmhosts = Get-vmhost
  41. # Multiple retries as some timeouts over long distance connections
  42. if ($null -eq $vmhosts) {
  43. write-host "Retrying "$VIServ
  44. $vmhosts = Get-vmhost
  45. }
  46. if ($null -eq $vmhosts) {
  47. write-host "Retrying "$VIServ
  48. $vmhosts = Get-vmhost
  49. }
  50. if ($null -ne $vmhosts) {
  51. $ReportRegion.ESXHosts = $vmhosts.count
  52. $report = @()
  53. get-vm | Where {$_.PowerState -eq "PoweredOn"} | Sort Name -Descending | get-view | % {
  54. $vm = "" | Select-Object Region,VMName,GuestVersion,VMVersion,NumCPU,MemoryMB,ipaddress,toolsstatus,toolsrunningstatus,toolsversion,GuestState,hostname,ESXHostID
  55. $vm.region = $Region
  56. $vm.VMName = $_.Name
  57. $vm.GuestVersion = $_.Config.GuestFullName
  58. $vm.VMVersion = $_.config.version
  59. $vm.NumCPU = $_.config.hardware.numcpu
  60. $vm.MemoryMB = $_.config.hardware.MemoryMB
  61. $vm.ipaddress = $_.guest.ipaddress
  62. $vm.toolsstatus = $_.guest.toolsstatus
  63. $vm.ToolsRunningStatus = $_.guest.ToolsRunningStatus
  64. $vm.ToolsVersion = $_.guest.ToolsVersion
  65. $vm.GuestState = $_.guest.GuestState
  66. $vm.hostname = $_.guest.hostname
  67. $vm.ESXHostID = $_.runtime.host.value
  68. $report += $vm
  69. }
  70. $vmfilename = "D:\vSphere\Reports\VM\Detail\"+$Region+"_"+$CurrentDate+"_"+$VIServ+"_VM_List.csv"
  71. $report | Export-Csv $vmfilename -noType
  72. $AllVMs += $Report
  73.  
  74. $ReportRegion.TotalVM = $report.count
  75. $ReportRegion.Win2000 = (@($report | Where {$_.GuestVersion -like "*Windows 2000*" }).Count)
  76. $ReportRegion.Win2003 = (@($report | Where {$_.GuestVersion -like "*Windows Server 2003*" }).Count)
  77. $ReportRegion.Win2008 = (@($report | Where {$_.GuestVersion -like "*Windows Server 2008*" }).Count)
  78. $ReportRegion.WinNT = (@($report | Where {$_.GuestVersion -like "*Windows NT*" }).Count)
  79. $ReportRegion.WinXP = (@($report | Where {$_.GuestVersion -like "*Windows XP*" }).Count)
  80. $ReportRegion.WinVista = (@($report | Where {$_.GuestVersion -like "*Windows Vista*" }).Count)
  81. $ReportRegion.Win7 = (@($report | Where {$_.GuestVersion -like "*Windows 7*" }).Count)
  82. $ReportRegion.RedHat = (@($report | Where {$_.GuestVersion -like "*Red Hat*" }).Count)
  83. $ReportRegion.Suse = (@($report | Where {$_.GuestVersion -like "*Suse*" }).Count)
  84. $ReportRegion.Solaris = (@($report | Where {$_.GuestVersion -like "*Solaris*" }).Count)
  85. $ReportRegion.Other = $report.count - $ReportRegion.Win2000 - $ReportRegion.Win2003 - $ReportRegion.Win2008 - $ReportRegion.WinNT - $ReportRegion.WinXP - $ReportRegion.WinVista - $ReportRegion.Win7 - $ReportRegion.RedHat - $ReportRegion.Suse - $ReportRegion.Solaris
  86. $ReportRegion.TotalWinSrv = $ReportRegion.Win2000 + $ReportRegion.Win2003 + $ReportRegion.Win2008 + $ReportRegion.WinNT
  87. }
  88. (get-view serviceinstance).Client.Logout()
  89. $ReportOutput += $ReportRegion
  90.  
  91. }
  92.  
  93. $Filename = "D:\vSphere\Reports\VM\"+$CurrentDate+"_ESX_VM_vCenter_Report.csv"
  94. $ReportOutput | Export-Csv $Filename -noType
  95.  
  96. $ReportRegion = $ReportOutput | group Region | select Name,
  97. @{Name="ESXHosts";Expression={($_.Group | Measure-Object -Sum ESXHosts).Sum }},
  98. @{Name="TotalVM";Expression={($_.Group | Measure-Object -Sum TotalVM).Sum }},
  99. @{Name="TotalWinSrv";Expression={($_.Group | Measure-Object -Sum TotalWinSrv).Sum }},
  100. @{Name="Win2000";Expression={($_.Group | Measure-Object -Sum Win2000).Sum }},
  101. @{Name="Win2003";Expression={($_.Group | Measure-Object -Sum Win2003).Sum }},
  102. @{Name="Win2008";Expression={($_.Group | Measure-Object -Sum Win2008).Sum }},
  103. @{Name="WinNT";Expression={($_.Group | Measure-Object -Sum WinNT).Sum }},
  104. @{Name="WinXP";Expression={($_.Group | Measure-Object -Sum WinXP).Sum }},
  105. @{Name="WinVista";Expression={($_.Group | Measure-Object -Sum WinVista).Sum }},
  106. @{Name="Win7";Expression={($_.Group | Measure-Object -Sum Win7).Sum }},
  107. @{Name="RedHat";Expression={($_.Group | Measure-Object -Sum RedHat).Sum }},
  108. @{Name="Suse";Expression={($_.Group | Measure-Object -Sum Suse).Sum }},
  109. @{Name="Solaris";Expression={($_.Group | Measure-Object -Sum Solaris).Sum }},
  110. @{Name="Other";Expression={($_.Group | Measure-Object -Sum Other).Sum }}
  111.  
  112. $Filename = "D:\vSphere\Reports\VM\"+$CurrentDate+"_ESX_VM_Region_Report.csv"
  113. $ReportRegion | Export-Csv $Filename -noType
  114.  
  115. $ReportPlatform = $ReportOutput | group Region | select Name,
  116. @{Name="ESXHosts";Expression={($_.Group |Measure-Object -Sum ESXHosts).Sum }},
  117. @{Name="WinSrv";Expression={($_.Group | Measure-Object -Sum TotalWinSrv).Sum }},
  118. @{Name="Linux";Expression={($_.Group | Measure-Object -Sum RedHat).Sum + ($_.Group | Measure-Object -Sum Suse).Sum }},
  119. @{Name="Solaris";Expression={($_.Group | Measure-Object -Sum Solaris).Sum }}
  120.  
  121. $Filename = "D:\vSphere\Reports\VM\"+$CurrentDate+"_ESX_VM_Platform_Report.csv"
  122. $ReportPlatform | Export-Csv $Filename -noType
  123.  
  124. $Filename = "D:\vSphere\Reports\VM\"+$CurrentDate+"_ALL_VM_Report.csv"
  125. $AllVMs | Export-Csv $Filename -noType

ESX DataStore info, to CSV and to SQL DB

April 8th, 2010

One of the bigest problems with ESX is how darn quickly VMs eat up SAN disk space, ive been toying with thin provisioning but the danger is you overprovision, run out of disk space then get into a real mess…

The info on storage useage isnt easy to see,or monitor, its a failing of vcenter… i wanted to extract the info so I could look at it, i 1st started with 1 script, which did one extract, i expanded it to do an extract daily, that wa becoming difficult to look at the history for trends, so i decided to add a SQL database and table and dump the info into SQL, from there I can trend it, report on datastores and hopefully then start using thin provisoning properly.

So I came up with a script to do this, its not perfectyet but it works.

  1. # vCenter ESX Host DataStore summary Report
  2. # John Gibson
  3. #
  4.  
  5. $vchosts = @()
  6. $vc = @()
  7. $ReportOutput = @()
  8. $ReportRegion = @()
  9. $ReportPlatform = @()
  10. $Decimals = 1
  11. $CurrentDate = get-date -format "yyyyMMdd"
  12. $YesterdayStart = (get-date -Hour 00 -Minute 00 -Second 00).adddays(-1)
  13. $YesterdayEnd = (get-date -Hour 23 -Minute 55 -Second 00).adddays(-1)
  14. $VIServ = 'vcenter.fqdn'
  15. $Region = 'Region'
  16.  
  17. Function Connect-SQL ($SqlQuery) {
  18. # Set the SQL Server
  19. $SqlServer = "SQLSERVER\INSTANCENAME"
  20. $SqlDatabase = "vcenterdatabase"
  21. $userid = 'dbuser'
  22. $userpass = 'dbpassword'
  23. # Setup SQL Connection
  24. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  25. $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlDatabase; Integrated Security = False; user=$userid; password=$userpass"
  26. # Setup SQL Command
  27. $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  28. $SqlCmd.CommandText = $SqlQuery
  29. $SqlCmd.Connection = $SqlConnection
  30. # Setup .NET SQLAdapter to execute and fill .NET Dataset
  31. $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  32. $SqlAdapter.SelectCommand = $SqlCmd
  33. $DataSet = New-Object System.Data.DataSet
  34. #Execute and Get Row Count
  35. $nRecs = $SqlAdapter.Fill($DataSet)
  36. if ($nRecs -gt 0)
  37. {
  38. # Do Stuff
  39. $dataSet.Tables | Select-Object -Expand Rows
  40. }
  41. }
  42.  
  43. $creds = New-Object System.Management.Automation.PsCredential(“AD\ADUSER”, (Get-Content “c:\mycred.crd” | ConvertTo-SecureString))
  44. $VIServer = Connect-VIServer -Server $VIServ -Credential $creds
  45.  
  46. $objHosts = @()
  47. $DataStores = get-datastore | get-view
  48.  
  49. if ($null -ne $DataStores) {
  50. foreach ($DataStore in $DataStores) {
  51. $objHost = "" | Select Region,Date,Name,CapacityGb,FreeSpaceGb,UncommittedGb,AllocatedGb,PercentAllocated,Accessible,MultipleHostAccess,Type,Version,BlockSizeMb
  52. write-host "Processing DataStore "$DataStore.Name
  53. $objHost.Region = $Region
  54. $objHost.Date = $CurrentDate
  55. $objHost.Name = $DataStore.Name
  56. $objHost.CapacityGb = [math]::round($DataStore.Summary.Capacity / 1Gb)
  57. $objHost.FreeSpaceGb = [math]::round($DataStore.Summary.FreeSpace / 1Gb)
  58. $objHost.UncommittedGb = [math]::round($DataStore.Summary.Uncommitted / 1Gb)
  59. $objHost.AllocatedGb = [math]::round(((($DataStore.Summary.Capacity - $DataStore.Summary.FreeSpace) + $DataStore.Summary.Uncommitted)) / 1Gb)
  60. $objHost.PercentAllocated = [math]::round(((($DataStore.Summary.Capacity - $DataStore.Summary.FreeSpace) + $DataStore.Summary.Uncommitted)*100)/$DataStore.Summary.Capacity,0)
  61. $objHost.Accessible = $DataStore.Summary.Accessible
  62. $objHost.MultipleHostAccess = $DataStore.Summary.MultipleHostAccess
  63. $objHost.Type = $DataStore.Info.vmfs.Type
  64. $objHost.Version = $DataStore.Info.vmfs.Version
  65. $objHost.BlockSizeMb = $DataStore.Info.vmfs.BlockSizeMb
  66. if ($null -eq $objHost.Type) {
  67. $objHost.Type = $DataStore.Info.nas.Type
  68. $objHost.Version = 0
  69. $objHost.BlockSizeMb = 0
  70. }
  71. $objHosts = $objHosts + $objHost
  72. }
  73. }
  74.  
  75. $Filename = "D:\vSphere\Reports\"+$CurrentDate+"_DataStore_Summary_Report.csv"
  76. $objHosts | Sort Name | Export-Csv $Filename -noType
  77. $Filename = "D:\vSphere\Reports\DataStore_Summary_Report.csv"
  78. $objHosts | Sort Name | Export-Csv $Filename -noType
  79.  
  80. # Write records to SQL Database
  81. write-host "Writing records to SQLDatabase"
  82. foreach ($ObjHost in $objHosts){
  83. $SqlWrite = "INSERT INTO HSBC_DataStores VALUES ('"+$ObjHost.Region+"', '"+$ObjHost.Date+"', '"+$ObjHost.Name+"', "+$ObjHost.CapacityGb+", "+$ObjHost.FreeSpaceGb+", "+$ObjHost.UncommittedGb+", "+$ObjHost.AllocatedGb+", "+$ObjHost.PercentAllocated+", '"+$ObjHost.Accessible+"', '"+$ObjHost.MultipleHostAccess+"', '"+$ObjHost.Type+"', '"+$ObjHost.Version+"', "+$ObjHost.BlockSizeMb+")"
  84. Connect-SQL $SqlWrite
  85. }
  86.  
  87. (get-view serviceinstance).Client.Logout()

Change local account passwords on ESX hosts

April 8th, 2010

I wanted to change the local passwords on all of my ESX and ESxi hosts recently, they are all the same, but I wanted to change them on a regular basis…  so I came up with a quick script to change them all.

  1. # Connect to the VI Server
  2. $erroractionpreference = "SilentlyContinue"
  3. Write-Host "Connecting to vCenter"
  4. Connect-VIServer "vcenter.fqdn" -user AD\ADuser -password 'ADPassword'
  5. $VMHosts = Get-VMHost | Sort-Object Name
  6. Disconnect-VIServer -Confirm:$False
  7. # Ive 2 local accounts I want to change...
  8.  
  9. $vmadminaccount = "vmadmin"
  10. $vmadminpassword = "C0mplexPassword1"
  11. $vmopsaccount = "vmops"
  12. $vmopspassword = "C0mplexPassword2"
  13.  
  14. # For each host, connect to the host as root, then change the passwords I want to change...
  15.  
  16. ForEach ($VMHost in $VMHosts)
  17. {
  18. $HostName = $VMHost.Name
  19.  
  20. $sgServer = Connect-VIServer -Server $HostName -User root -Password RootPassword
  21. Write-host "Changing passwords on " $HostName
  22.  
  23. # if ESX then allow Shell Access, if not then dont...
  24. $ESXHost = get-vmhost | get-view
  25. If ($ESXHost.Config.Product.name -ne "VMware ESXi"){
  26. $Access = $true
  27. } Else {
  28. $Access = $false
  29. }
  30.  
  31. New-VMHostAccount -Group $vmadminaccount
  32. Set-VMHostAccount -UserAccount $vmadminaccount -password $vmadminpassword -Description "VMware Local ESXi Administrator" -AssignGroups $vmadminaccount -GrantShellAccess $Access
  33.  
  34. New-VMHostAccount -Group $vmopsaccount
  35. Set-VMHostAccount -UserAccount $vmopsaccount -password $vmopspassword -Description "VMware Local ESXi Operations Administrator" -AssignGroups $vmopsaccount -GrantShellAccess $Access
  36.  
  37. Disconnect-VIServer -Confirm:$false
  38.  
  39. }

ESX host and VM inventory info to CSV via vCenter

April 8th, 2010

Im always wanting inventory extracts for various reasons, this was one of my 1st scripts to connect to vCenter and extract the ESX andVM inventory info I wanted and dump the info into CSV files…  I run this daily via scheduled tasks.

  1. # vCenter ESX Host detail Report
  2. # Connects to vCenter
  3. # Gets the Hosts and writes host details to a CSV
  4. # Then gets the VMs and writes the VMs to a CSV
  5. # John Gibson
  6. #
  7.  
  8. # Connect to vCenter server using credentials for AD account stored in cred file.
  9. $Decimals = 1
  10. $ReportOutput = @()
  11. $VIServ = 'vcenter.fqdn'
  12. $Region = 'RegionName'
  13. $creds = New-Object System.Management.Automation.PsCredential(“AD\ADAccont”, (Get-Content “c:\mycred.crd” | ConvertTo-SecureString))
  14. $VIServer = Connect-VIServer -Server $VIServ -Credential $creds
  15.  
  16. # ve had some timeouts so retry...
  17. if ($null -eq $VIServer) {
  18. write-host "Retrying Connect to "$VIServ
  19. $VIServer = Connect-VIServer -Server $VIServ -Credential $creds
  20. }
  21.  
  22. # Getthe VM hosts
  23. $objHosts = @()
  24. $vmhosts = Get-vmhost
  25. if ($null -eq $vmhosts) {
  26. write-host "Retrying "$VIServ
  27. $vmhosts = Get-vmhost
  28. }
  29.  
  30. # for each host get the inventory info I want...
  31. foreach ($vmhost in $vmhosts) {
  32. $vmhostview = $vmhost | Get-View
  33. $objHost = "" | Select Region,Name,OSType,OSFullName,OSVersion,OSBuild,Vendor,Model,UUID,MemorySize,CpuModel,CpuMHz,NumCPuPkgs,NumCPuCores,VmotionEnabled,ESXHostID,ClusterID
  34. write-host "Processing Host for "$vmhostview.Name
  35. $objHost.Region = $Region
  36. $objHost.Name = $vmhostview.Name
  37. $objHost.OSType = $vmhostview.Config.product.Name
  38. $objHost.OSFullName = $vmhostview.Config.product.FullName
  39. $objHost.OSVersion = $vmhostview.Config.product.Version
  40. $objHost.OSBuild = $vmhostview.Config.product.Build
  41. $objHost.Vendor = $vmhostview.summary.hardware.Vendor
  42. $objHost.Model = $vmhostview.summary.hardware.Model
  43. $objHost.UUID = $vmhostview.summary.hardware.UUID
  44. $objHost.MemorySize = ([int]($vmhostview.summary.hardware.MemorySize / 1MB))
  45. $objHost.CpuModel = $vmhostview.summary.hardware.CpuModel
  46. $objHost.CpuMhz = $vmhostview.summary.hardware.CpuMhz
  47. $objHost.NumCPuPkgs = $vmhostview.summary.hardware.NumCPuPkgs
  48. $objHost.NumCPuCores = $vmhostview.summary.hardware.NumCPuCores
  49. $objHost.VmotionEnabled = $vmhostview.summary.config.VmotionEnabled
  50. $objHost.ESXHostID = $vmhostview.moref.value
  51. $objHost.ClusterID = ($vmhost | Get-Cluster).Name
  52. $objHosts = $objHosts + $objHost
  53. }
  54.  
  55. # Write host inventory to a CSV...
  56. $Filename = "D:\vSphere\Reports\"+$Region+"_ESX_Host_Report.csv"
  57. $objHosts | Export-Csv $Filename -noType
  58.  
  59. # Get the VMs and get the info i want for each VM...
  60. $ReportRegion.ESXHosts = $vmhosts.count
  61. $report = @()
  62. get-vm | Where {$_.PowerState -eq "PoweredOn"} | Sort Name -Descending | get-view | % {
  63. $vm = "" | Select-Object Region,VMName,GuestVersion,VMVersion,NumCPU,MemoryMB,ipaddress,toolsstatus,toolsrunningstatus,toolsversion,GuestState,hostname,ESXHostID,DatastoreCommittedGb,DatastoreUncommittedGb,DatastoreTotalGb
  64. $vm.region = $Region
  65. $vm.VMName = $_.Name
  66. $vm.GuestVersion = $_.Config.GuestFullName
  67. $vm.VMVersion = $_.config.version
  68. $vm.NumCPU = $_.config.hardware.numcpu
  69. $vm.MemoryMB = $_.config.hardware.MemoryMB
  70. $vm.ipaddress = $_.guest.ipaddress
  71. $vm.toolsstatus = $_.guest.toolsstatus
  72. $vm.ToolsRunningStatus = $_.guest.ToolsRunningStatus
  73. $vm.ToolsVersion = $_.guest.ToolsVersion
  74. $vm.GuestState = $_.guest.GuestState
  75. $vm.hostname = $_.guest.hostname
  76. $vm.ESXHostID = $_.runtime.host.value
  77. $vm.DatastoreCommittedGB = [math]::round($_.Summary.Storage.Committed / 1Gb)
  78. $vm.DatastoreUncommittedGb = [math]::round($_.Summary.Storage.Uncommitted / 1Gb)
  79. $vm.DatastoreTotalGb = $vm.DatastoreCommittedGB + $vm.DatastoreUncommittedGb
  80. $report += $vm
  81. }
  82.  
  83. # Write the VM inventory to a CSV...
  84. $vmfilename = "D:\vSphere\Reports\"+$Region+"_VM_List.csv"
  85. $report | Export-Csv $vmfilename -noType
  86.  
  87. # Disconnect from vCenter
  88. (get-view serviceinstance).Client.Logout()

Cannot remove ESX host from vCenter

April 8th, 2010

I hit a problem today, was trying to remove a few hosts from vCenter but they Remove was greyed out, couldnt figure out what was going on, then i thought PowerCLI…

connect-viserver vCenter

Remove-VMHost -VMHost <hostname>

sorted!

ESXi PowerCLi Config Script

March 30th, 2010

Ive been working on an ESXi Host build recently, the manual build was getting annoying so I decided to script everything past the part where you boot the ISO, give the host a password, name and IP details… once its on the network I used to attach it to vCenter and finish off the config manually… this bit ive now scripted:

  1. # SAMPLE - Change variables for your Site
  2. #
  3. # VMware PowerCLI Script to configure a VMware ESXi Host
  4. # Designed for VMware ESXi on HP 460c G6 Blades
  5. # But should work for most hosts with some variable changes
  6. # Will work with an IP address but the storage will be renamed to XX.XX.XX.X-LOCAL instead of HOSTNAME-LOCAL
  7. # Host should be deployed from ISO
  8. # Assumes root password and IP Details configured (IP, DNS and search suffix)
  9. # At that point when the host is on the network this script can be run
  10. # Once this script is complete, add the host to vCenter and reboot the host and
  11. # then validate the host is configured correctly.
  12. #
  13. # John Gibson - March 2010
  14. # version 1.0 - Initial script creation
  15. # version 1.1 - Updated script to set DNS Settings on Hosts
  16. # version 1.2 - Updated script and structure of script
  17. #
  18.  
  19. # Set Variables to be used in the ESXi Host configuration
  20. #
  21. # Modify these settings for regional requirements
  22. #
  23.  
  24. # ESXi Host Patch repository where the offline bundles have been extracted to
  25. $patchURL = "http://servername.fqdn"
  26.  
  27. # NTP Time Servers to use
  28. $ntp1 = "your.NTP.Server1.fqdn"
  29. $ntp2 = "your.NTP.Server1.fqdn"
  30.  
  31. # DNS Search Details to use
  32. $DomainName = "host.dns.doman.name"
  33. $DNSSearch = "host.dns.search.name"
  34. $PreferredDNS = "x.x.x.x"
  35. $AltDNS = "x.x.x.x"
  36.  
  37. # These NICs are connected to the management network vSwitch0
  38. $esxnics = "vmnic0","vmnic1"
  39.  
  40. # This/these NICs are connected to the VM network vSwitch1
  41. $vmnics = "vmnic2","vmnic3"
  42.  
  43. # VMotion Subnet Mask
  44. $VMotionSubnet = "255.255.255.0"
  45.  
  46. # Local Accounts to be created with VMware Admin Rights
  47. # Note: Complex passwords are needed or ESXi will reject them
  48. $vmadminaccount = "vmadmin"
  49. $vmadminpassword = "C0mp1exPassw0rd"
  50. $vmopsaccount = "vmops"
  51. $vmopspassword = "C0mp1exPassw0rd"
  52. $eccuserpassword = "C0mp1exPassw0rd"
  53.  
  54. Write-Host "ESXi Configuration script for VMware ESXi Hosts for HP Servers"
  55.  
  56. # Capture unique variables for the ESXi Host by user input
  57. $vmhost=(Read-Host "Enter just the name of the ESXi Host (e.g. hostname)").ToLower()
  58. $HostPassword=Read-Host "Enter the password to the root account on the ESXi Host"
  59. $VMotionIP=Read-Host "Enter the VMotion IP address for this ESX Host (x.x.x.x)"
  60. $vSwitch1Name=Read-Host "Enter the name of the Virtual Machine network (e.g. 192.168.10.1 Subnet)"
  61. $vSwitch1VLAN=Read-Host "Enter the number of the Virtual Machine VLAN (0 if not trunked)"
  62. if ("0" -ne $vSwitch1VLAN){
  63. $vSwitch1Name2=Read-Host "Enter the name of the Second Virtual Machine network (Press 0 to skip)"
  64. if ("0" -ne $vSwitch1Name2){
  65. $vSwitch1VLAN2=Read-Host "Enter the number of the Second Virtual Machine VLAN"
  66. }
  67. }
  68.  
  69. # Authenticate to ESX Host...
  70. write-host "Connecting to " $vmhost
  71. $esxhost = Connect-VIServer $vmhost -User root -Password $HostPassword
  72.  
  73. # First puts the ESX host into maintenance mode...
  74. write-host "Entering Maintenance Mode"
  75. Set-VMHost -State maintenance
  76.  
  77. # Configure vSwitch0
  78. write-host "Configuring vSwitch0"
  79. $vs0 = Get-VirtualSwitch -Name vSwitch0
  80. Set-VirtualSwitch -VirtualSwitch $vs0 -Nic $esxnics
  81. New-VMHostNetworkAdapter -PortGroup VMkernel -VirtualSwitch $vs0 -IP $VMotionIP -SubnetMask $VMotionSubnet -VMotionEnabled: $true
  82.  
  83. # Removes "VM Network" from the vSwitch0
  84. get-VirtualPortGroup | where { $_.Name -like "VM Network"} | Remove-VirtualPortGroup -Confirm:$false
  85.  
  86. # Configure vSwitch1
  87. write-host "Configuring vSwitch1"
  88. $vs1 = New-VirtualSwitch -Name vSwitch1 -nic $vmnics
  89. write-host "Configuring " $vSwitch1Name
  90. New-VirtualPortGroup -VirtualSwitch $vs1 -Name $vSwitch1Name -VLanId $vSwitch1VLAN
  91. if ("0" -ne $vSwitch1VLAN){
  92. if ("0" -ne $vSwitch1Name2){
  93. write-host "Configuring " $vSwitch1Name2
  94. New-VirtualPortGroup -VirtualSwitch $vs1 -Name $vSwitch1Name2 -VLanId $vSwitch1VLAN2
  95. }
  96. }
  97.  
  98. # Configure vSwitch Security for all vSwitches
  99. write-host "Configuring vSwitch Security settings and enabling Beacon Probing for all vSwitches"
  100. foreach ($vswitchName in Get-VirtualSwitch $vmhost){
  101. $hostview = get-vmhost $vmhost | Get-View
  102. $ns = Get-View -Id $hostview.ConfigManager.NetworkSystem
  103. $vsConfig = $hostview.Config.Network.Vswitch | Where-Object { $_.Name -eq $vswitchName }
  104. $vsSpec = $vsConfig.Spec
  105. $vsSpec.Policy.NicTeaming.FailureCriteria.checkBeacon = $true
  106. $vsSpec.Policy.Security.AllowPromiscuous = $False
  107. $vsSpec.Policy.Security.forgedTransmits = $False
  108. $vsSpec.Policy.Security.macChanges = $False
  109. $ns.UpdateVirtualSwitch( $VSwitchName, $vsSpec)
  110. }
  111.  
  112. # Set-up the NTP Configuration
  113. write-host "Adding NTP Servers"
  114. Add-VmHostNtpServer -NtpServer $ntp1,$ntp2
  115.  
  116. # Set DNS Details to ensure they have been set
  117. write-host "Resetting DNS Details"
  118. $vmHostNetworkInfo = Get-VmHostNetwork -VMHost $vmhost
  119. Set-VmHostNetwork -Network $vmHostNetworkInfo -DomainName $DomainName -SearchDomain $DNSSearch
  120. Set-VmHostNetwork -Network $vmHostNetworkInfo -DnsAddress $PreferredDNS, $AltDNS
  121.  
  122. # Rename Local Datastore
  123. $LocalName = $vmhost.ToUpper()
  124. Get-Datastore -Name "datastore1" | Set-Datastore -Name $LocalName"-LOCAL"
  125.  
  126. # Create Local Accounts
  127. write-host "Configuring local ESXi account for " $vmadminaccount
  128. New-VMHostAccount -Group $vmadminaccount
  129. New-VMHostAccount -User -Id $vmadminaccount -Password $vmadminpassword -Description "VMware Local ESXi Administrator" -AssignGroups $vmadminaccount
  130. $sgAuthMgr = Get-View (Get-View ServiceInstance).Content.AuthorizationManager
  131. $sgEntity = Get-Folder ha-folder-root | Get-View
  132. $sgPerm = New-Object VMware.Vim.Permission
  133. $sgPerm.entity = $sgEntity.MoRef
  134. $sgPerm.group = $true
  135. $sgPerm.principal = $vmadminaccount
  136. $sgPerm.propagate = $true
  137. $sgPerm.roleId = ($sgAuthMgr.RoleList | where {$_.Name -eq "Admin"}).RoleId
  138. $sgAuthMgr.SetEntityPermissions($sgEntity.MoRef,$sgPerm)
  139.  
  140. write-host "Configuring local ESXi account for " $vmopsaccount
  141. New-VMHostAccount -Group $vmopsaccount
  142. New-VMHostAccount -User -Id $vmopsaccount -Password $vmopspassword -Description "VMware Local ESXi Operations Administrator" -AssignGroups $vmopsaccount
  143. $sgAuthMgr = Get-View (Get-View ServiceInstance).Content.AuthorizationManager
  144. $sgEntity = Get-Folder ha-folder-root | Get-View
  145. $sgPerm = New-Object VMware.Vim.Permission
  146. $sgPerm.entity = $sgEntity.MoRef
  147. $sgPerm.group = $true
  148. $sgPerm.principal = $vmopsaccount
  149. $sgPerm.propagate = $true
  150. $sgPerm.roleId = ($sgAuthMgr.RoleList | where {$_.Name -eq "Admin"}).RoleId
  151. $sgAuthMgr.SetEntityPermissions($sgEntity.MoRef,$sgPerm)
  152.  
  153. # Create Account for EMC ECC Control Centre
  154.  
  155. write-host "Configuring account for EMC ECC ControlCenter"
  156. $sgRole = New-VIRole -Name ControlCenter -Privilege ( Get-VIPrivilege -PrivilegeItem "Browse datastore" )
  157. New-VMHostAccount -Group ControlCenter
  158. New-VMHostAccount -User -Id eccuser -Password $eccuserpassword -Description "EMC ControlCenter discovery" -AssignGroups "ControlCenter"
  159. $sgAuthMgr = Get-View (Get-View ServiceInstance).Content.AuthorizationManager
  160. $sgEntity = Get-Folder ha-folder-root | Get-View
  161. $sgPerm = New-Object VMware.Vim.Permission
  162. $sgPerm.entity = $sgEntity.MoRef
  163. $sgPerm.group = $true
  164. $sgPerm.principal = "ControlCenter"
  165. $sgPerm.propagate = $true
  166. $sgPerm.roleId = ($sgAuthMgr.RoleList | where {$_.Name -eq "ControlCenter"}).RoleId
  167. $sgAuthMgr.SetEntityPermissions($sgEntity.MoRef,$sgPerm)
  168.  
  169. # Patch ESXi Host
  170. write-host "Patching ESXi Host"
  171. Install-VMHostPatch -VMhost $vmhost -HostUsername root -HostPassword $HostPassword -WebPath $patchURL/patch/ESXi400-201002001/metadata.zip
  172. Install-VMHostPatch -VMhost $vmhost -HostUsername root -HostPassword $HostPassword -WebPath $patchURL/patch/BCM-bnx2x-1.52.12.v40.3-offline_bundle-223054/metadata.zip
  173. Install-VMHostPatch -VMhost $vmhost -HostUsername root -HostPassword $HostPassword -WebPath $patchURL/patch/hp-esxi4.0uX-bundle-1.2/metadata.zip
  174.  
  175. # Restart the ESXi Host
  176. write-host "Rebooting ESXi Host"
  177. Restart-VMHost -server $vmhost -confirm:$false
  178.  
  179. # Disconnect from ESXi Host
  180. Disconnect-VIServer -Confirm:$False
  181.  
  182. # Provide Post config Instructions
  183. write-host "The basic ESXi Host configuration is completed, please:"
  184. write-host "1. Wait for the host to reboot."
  185. write-host "2. Connect the Host to vCenter and assign a license"
  186. write-host "3. Verify the Host Configuration is correct"
  187. write-host "4. Confirm all patches have been applied (scan for updates)"
  188. Write-Host "5. Once complete take the ESXi host out of Maintenance Mode"

ESXi Host SSL Certificates

March 30th, 2010

I hit a problem this week with ESXi hosts and their self signed SSL Certificates. If you point a browser at your ESXi host and have a look at the SSLcert you will see that it is issued to “localhost.localdomain”  in most scenarios this is not a problem but we hit a problem with EMC ECC ControlCenter.

ControlCenter is the EMC product that looks via vCenter and connects to the ESXi hosts and gathers storage usage info… all fine but it doesnt like the vmware default SSL certificate.

The certificate has o be updated to be issued by the hostname.

To do this is darn annoying, you cant re-generate them remotely, you have to go onto the console.

First put the Host into Maintenance Mode.

Then open a Console to the server, once there  Press F1, and then type “unsupported” to get into the Technical Support mode console.

From there tpe:

/sbin/generate-certificates.sh

then either reboot or type

/ebin/services.sh restart.

You then once rebooted have to reconnect the host back into vCenter and reauthenticate with an admin account on the host to allow vCenter to reconnect.

Interestingly I found that if you delete the SSLcertificate VMware will recreate one, but not wih the hostnme in it but again with localhost.localdomain… so an ESXi host will never have a valid self signed SSL certificate unless you manually run generate-certificates.sh