├── README.md ├── Change-VM-UUID.ps1 ├── Disconnect_from_vCenter.ps1 ├── List-Specfic-VM-Nic.ps1 ├── In Development ├── ExportDRSRules.ps1 ├── ResetLimits.ps1 ├── ImportDRSRules.ps1 ├── ToolsVersion.ps1 ├── ExportVMLocations.ps1 ├── Re-establish_SysLog_Connection.ps1 ├── PerenniallySetRDMs.ps1 ├── ReloadSysLog.ps1 ├── Match Selected and Installed OS.ps1 ├── svMotionVMs.ps1 ├── EnableSNMP.ps1 ├── DoNotUpdateVMtoInstallToolsonReboot.ps1 ├── AddVLANids.ps1 ├── UpdateVMtoInstallToolsonReboot.ps1 ├── CreatevSwitch.ps1 ├── EnableFTLogging.ps1 ├── DetachSCSILUN.ps1 ├── Query_vRAM.ps1 ├── ChangeDRSVLANs.ps1 ├── ConfigDRvSwitch0.ps1 ├── CopyvSwitchFromHosttoHost.ps1 ├── Get-vSphere5Licenses.ps1 ├── vSphere 4.1 Hardening -- Guest VMs.ps1 └── vSphere4.1Hardening - origingal download.ps1 ├── Remove-Snapshot.ps1 ├── Get-VM-VLan.ps1 ├── testing.ps1 ├── Update_Tools ├── StartedEmail.ps1 ├── CompletedEmail.ps1 ├── UpdateTools.ps1 └── UpdateToolsbyHosts.ps1 ├── ReloadSyslog.ps1 ├── GetPathStatus.ps1 ├── SetNTP.ps1 ├── SetSyslog.ps1 ├── TEST.ps1 ├── Send-Email.ps1 ├── ExtendVMDKandGuest.ps1 ├── Unused-LUNS.ps1 ├── Get-VMSnapshots.ps1 ├── Get-VM-IP-VLAN.ps1 ├── Get-HostiSCSIIQN.ps1 ├── Cluster-Get-VM-Information.ps1 ├── Get-Host-NICs.ps1 ├── Propogate-vSwitch-Settings.ps1 ├── Get-Datacenter-VMs_Info.ps1 ├── RDM-Listing.ps1 ├── Create-Snapshot.ps1 ├── AddVLANID.ps1 ├── Attach-SCSILun.ps1 ├── CloneVMs.ps1 ├── Detach-SCSILun.ps1 ├── Copy-From-Datastore.ps1 ├── Datacenter-Get-VM-Storage.ps1 ├── GUI-Storage-vMotion.ps1 ├── ESXi-Shutdown-Hosts-and-VMs.ps1 ├── Set-vSwitch-Settings.ps1 ├── Power-On-VMs.ps1 ├── vCheck └── snapshot-info.ps1 ├── Remove-Orphaned-Files.ps1 ├── Get-LLDPCDPInfo.ps1 ├── Get-vSwitch-Security.ps1 ├── DatastoreFunction.ps1 ├── DatastoreFunction.txt ├── Resource-Pool-Pie.ps1 ├── Get-NICAndFirmware.ps1 ├── Power-Off-VMs.ps1 ├── Detach-RDM-from-Host.ps1 ├── ESXi-Set-NTP.ps1 └── CPReport-v2.1-Community-Edition.ps1 /README.md: -------------------------------------------------------------------------------- 1 | # PowerCLI 2 | Repo for all PowerCLI scripts for vSphere automation. 3 | -------------------------------------------------------------------------------- /Change-VM-UUID.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/voletri/PowerCLI-1/HEAD/Change-VM-UUID.ps1 -------------------------------------------------------------------------------- /Disconnect_from_vCenter.ps1: -------------------------------------------------------------------------------- 1 | #Disconnect from vCenter 2 | Disconnect-VIServer -Confirm:$false -------------------------------------------------------------------------------- /List-Specfic-VM-Nic.ps1: -------------------------------------------------------------------------------- 1 | Get-VM | Get-NetworkAdapter | 2 | Where-object {$_.Type -ne "Vmxnet3"} | 3 | Select @{N="VM";E={$_.Parent.Name}},Name,Type | 4 | export-Csv c:\Network_Interface.csv -NoTypeInformation -------------------------------------------------------------------------------- /In Development/ExportDRSRules.ps1: -------------------------------------------------------------------------------- 1 | # Export DRS rules to txt file. 2 | # v.1 -- 1/23/2012 - Eric TeKrony 3 | 4 | # Export DRS Rules 5 | Get-Cluster -Name "LDNEDC4" | Get-DrsRule | Export-CliXml 'D:\Script_Repo\CSVs\DRS-LDNEDC4.xml' -------------------------------------------------------------------------------- /Remove-Snapshot.ps1: -------------------------------------------------------------------------------- 1 | # Remove all snapshots on the VM called PROD1 2 | 3 | #Connect-VIServer MYVISERVER 4 | 5 | $vm = Read-Host "Enter VM name" 6 | Write-Host " " 7 | 8 | Get-VM $vm | Get-Snapshot | Remove-Snapshot -confirm:$True 9 | 10 | Write-Host " " -------------------------------------------------------------------------------- /In Development/ResetLimits.ps1: -------------------------------------------------------------------------------- 1 | # Reset Memory and CPU Limits to unlimited. 2 | # v.1 -- 1/27/2012 -- Eric TeKrony 3 | 4 | Get-VM | Where-Object {($_.MemLimitMB -ne "-1") -or ($_.CpuLimitMhz -ne "-1")} | ` 5 | Get-VMResourceConfiguration | Set-VMResourceConfiguration -MemLimitMB $null -CpuLimitMhz $null 6 | 7 | -------------------------------------------------------------------------------- /Get-VM-VLan.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes 2 | #: October 29, 2015 3 | 4 | # Script to obtain a specific VM's VLAN ID. 5 | # Eventually will allow for single VM, VMs on specific cluster, VMs on datacenter, etc. 6 | 7 | $vm = Read-Host "Enter the VM you wish to check VLAN info for" 8 | 9 | get-vm -name $vm | Get-VirtualPortGroup | select Name, VLanId -------------------------------------------------------------------------------- /testing.ps1: -------------------------------------------------------------------------------- 1 | $cluster = "OMAEDC" 2 | $esxhost = Get-Cluster $cluster | Get-VMHost 3 | 4 | $id = Read-Host "enter id" 5 | 6 | foreach($ds in $esxhost | ` 7 | Get-Datastore | where{$_.Type -eq "disk"} | Get-View){ 8 | 9 | $ds.Info.Disk.Extent | %{ 10 | if($_.DiskName -eq $id){ 11 | Write-Host $ds.Info.Name $_.DiskName 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /In Development/ImportDRSRules.ps1: -------------------------------------------------------------------------------- 1 | # Import DRS rules from txt file. 2 | # v.1 -- 1/23/2012 - Eric TeKrony 3 | 4 | # Import DRS 5 | ForEach ($rule in (Import-CliXml 'D:\Script_Repo\CSVs\DRS-LDNEDC4.xml')){ 6 | New-DrsRule -Cluster (Get-Cluster -Name "LDNEDC4") ` 7 | -Name $rule.Name -Enabled $rule.Enabled ` 8 | -KeepTogether $rule.KeepTogether ` 9 | -VM (Get-VM -Id $rule.VmIds)} -------------------------------------------------------------------------------- /In Development/ToolsVersion.ps1: -------------------------------------------------------------------------------- 1 | $server = "144.210.196.99" 2 | $user = "ipgna\esb.service" 3 | $pwd = "Password1" 4 | 5 | Connect-VIServer $server -User $user -Password $pwd 6 | 7 | Get-cluster DRSSAP4 | get-vm | % { get-view $_.ID } | where {$_.guest.toolsstatus -eq "toolsOld"} | select Name, 8 | @{ Name="ToolsStatus"; Expression={$_.guest.toolsstatus}}, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}} -------------------------------------------------------------------------------- /Update_Tools/StartedEmail.ps1: -------------------------------------------------------------------------------- 1 | #Set Date format for emails 2 | $timestart = (Get-Date -f "T") 3 | 4 | $emailFrom = "zach.milleson@interpublic.com" 5 | $emailTo = "zach.milleson@interpublic.com" 6 | $subject = "VMTools upgrade has begun" 7 | $body = "Time Started:", $timestart 8 | 9 | $smtpServer = "omaedcmgw002.interpublic.com" 10 | $smtp = new-object Net.Mail.SmtpClient($smtpServer) 11 | $smtp.Send($emailFrom,$emailTo,$subject,$body) -------------------------------------------------------------------------------- /Update_Tools/CompletedEmail.ps1: -------------------------------------------------------------------------------- 1 | #Set Date format for emails 2 | $timecomplete = (Get-Date -f "T") 3 | 4 | $emailFrom = "zach.milleson@interpublic.com" 5 | $emailTo = "zach.milleson@interpublic.com" 6 | $subject = "VMTools Upgrade has finished" 7 | $body = "Time Completed:", $timecomplete 8 | 9 | $smtpServer = "omaedcmgw002.interpublic.com" 10 | $smtp = new-object Net.Mail.SmtpClient($smtpServer) 11 | $smtp.Send($emailFrom,$emailTo,$subject,$body) -------------------------------------------------------------------------------- /ReloadSyslog.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for reloading syslogserver on hosts 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | # Setup common variables to use 6 | $vcenter = "vcenter.lab.local" 7 | 8 | # Connect to vCenter 9 | Connect-VIServer -Server $vcenter 10 | 11 | # Get hosts 12 | $vmhosts = @(Get-VMHost) 13 | 14 | # Configure syslog on each host in vCenter 15 | foreach ($vmhost in $vmhosts) { 16 | $esxcli = Get-EsxCli -VMHost $vmhost 17 | $esxcli.system.syslog.reload() 18 | } 19 | -------------------------------------------------------------------------------- /In Development/ExportVMLocations.ps1: -------------------------------------------------------------------------------- 1 | # Export all VMs in a cluster and their locations v.1 2 | # This script will export all VMs in a cluster and export it to a CSV. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 11/15/2012 7 | 8 | 9 | #Prompt user for cluster 10 | $cluster = Read-Host "Enter Cluster" 11 | 12 | Get-Cluster $cluster | Get-VM | Select Name, @{N="Cluster";E={Get-Cluster -VM $_}}, @{N="ESX Host";E={Get-VMHost -VM $_}}, @{N="Datastore";E={Get-Datastore -VM $_}} | ` 13 | Export-Csv -NoTypeInformation "D:\Output\"$cluster + "_VMs.csv" -------------------------------------------------------------------------------- /Update_Tools/UpdateTools.ps1: -------------------------------------------------------------------------------- 1 | # Upgrade VMTools on VMs from a CSV 2 | # Created by Zach Milleson 3 | # Revision 1.0 4 | 5 | #Connect to vCenter 6 | D:\Script_Repo\Connect_to_DRS_vCenter.ps1 7 | 8 | #Send Start Email 9 | D:\Script_Repo\Update_Tools\StartedEmail.ps1 10 | 11 | $vms = Import-CSV "D:\Script_Repo\Update_Tools\UpdateTools.csv" 12 | foreach ($vm in $vms){ 13 | Get-VM $vm.name | Update-Tools -NoReboot 14 | } 15 | 16 | #Send Finish Email 17 | D:\Script_Repo\Update_Tools\CompletedEmail.ps1 18 | 19 | #Disconnect from vCentre 20 | D:\Script_Repo\Disconnect_from_vCenter.ps1 -------------------------------------------------------------------------------- /GetPathStatus.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for getting path selection policy for hosts 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | # Setup common variables to use 6 | $vcenter = "vcenter.lab.local" 7 | 8 | # Connect to vCenter 9 | Connect-VIServer -Server $vcenter 10 | 11 | $vmhosts = @(Get-VMHost) 12 | foreach ($vmhost in $vmhosts) { 13 | $esxcli = Get-EsxCli -VMHost $vmhost 14 | $status = $esxcli.storage.nmp.device.list($null) | Select Device, DeviceDisplayName, PathSelectionPolicy 15 | Write-Host "===================================" 16 | Write-Host "$vmhost" 17 | $status 18 | Write-Host "===================================" 19 | 20 | } 21 | -------------------------------------------------------------------------------- /In Development/Re-establish_SysLog_Connection.ps1: -------------------------------------------------------------------------------- 1 | #Re-enable Syslog Reporting v.1 2 | #This script re-establishes the Syslog collecting from the hosts to the vCenter Server. Each time the vCenter server is restarted, this will need to be run. 3 | # 4 | #Written by Zach Milleson 5 | # 6 | #v.1 5/28/2013 7 | 8 | #Prompt user for cluster 9 | $cluster = Read-Host "Enter Cluster" 10 | 11 | #Gather hosts from vCenter for chosen cluster 12 | $MyVMHosts = Get-Cluster $cluster | Get-VMHost | sort Name | % {$_.Name} 13 | 14 | foreach ($hostname in $MyVMHosts){ 15 | Write-Host "ESX: "$hostname 16 | $esxcli = Get-EsxCli -VMhost $hostname 17 | $esxcli.system.syslog.reload() 18 | } -------------------------------------------------------------------------------- /In Development/PerenniallySetRDMs.ps1: -------------------------------------------------------------------------------- 1 | # Set Perennially Reserved LUNs v.1 2 | # This script sets the LUNs used as RDMs for Microsoft Clusters as reserved. This speeds up boot time of the ESX Host. 3 | # Written by: Eric TeKrony 4 | # 5 | # 04/24/2012 -- v.1 6 | 7 | 8 | # Get the hosts in the cluster 9 | $vmhosts = Get-Cluster "OMAEDC_i5" | Get-VMHost 10 | 11 | # Get the lunIDs from text file 12 | $lunids = Import-Csv "D:\Script_Repo\CSVs\omaedc5RDMs.csv" 13 | 14 | foreach ($vmhost in $vmhosts) 15 | { 16 | $myesxcli = Get-EsxCli -VMHost $vmhost 17 | 18 | foreach ($lunid in $lunids) 19 | { 20 | $myesxcli.storage.core.device.setconfig($false, $lunid, $true) 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /In Development/ReloadSysLog.ps1: -------------------------------------------------------------------------------- 1 | #SysLog Restart Script 2 | #This script passes the ESXCLI command to reload the syslog daemon on the host. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 2/8/2013 7 | 8 | #Prompt user for datacenter and cluster 9 | $datacenter = Read-Host "Enter Datacenter" 10 | #$cluster = Read-Host "`Enter Cluster" 11 | 12 | #Gather hosts from vCenter for chosen cluster 13 | Write-Host "Getting hosts from vCenter Server..." 14 | $MyVMHosts = Get-DataCenter | Get-VMHost 15 | 16 | #Run command on each host. 17 | foreach ($hostname in $MyVMHosts) { 18 | $esxCli = Get-EsxCli -VMHost $hostname 19 | $esxCli.system.syslog.reload 20 | Write-Host "$hostname...done." 21 | } -------------------------------------------------------------------------------- /SetNTP.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for adding ntp to hosts 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | # Setup common variables to use 6 | $vcenter = "vc.lab.local" 7 | 8 | # Connect to vCenter 9 | Connect-VIServer -Server $vcenter 10 | 11 | #Set NTP server for all hosts 12 | Get-VMHost | Add-VMHostNTPServer -NTPserver us.pool.ntp.org 13 | 14 | #Restart NTP services on host 15 | Get-VMHost | Get-VMHostService | Where-Object {$_.key -eq "ntpd"} | Stop-VMHostService 16 | Get-VMHost | Get-VMHostService | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService 17 | 18 | #Set service to start automatically 19 | Get-VMHost | Get-VMHostService | Where-Object {$_.key -eq "ntpd"} | Set-VMHostService -policy "on" 20 | -------------------------------------------------------------------------------- /In Development/Match Selected and Installed OS.ps1: -------------------------------------------------------------------------------- 1 | #Match Selected OS to Installed OS v.1 2 | #This script will match the Selected OS to the installed OS. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 10/13/2011 7 | 8 | #Get Guest machines from CSV file 9 | $vmguests = import-csv "D:\Script_Repo\CSVs\MatchOSTest.csv" 10 | 11 | #Create new Virtual Machince Config Spec 12 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 13 | 14 | #Write new config options to VMs using csv 15 | foreach ($vm in $vmguests){ 16 | 17 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 18 | $vmConfigSpec.guestId = $vm.OS 19 | 20 | Get-VM $vm.Name | %{Get-View $_.ID}| %{$_.ReconfigVM_Task($vmConfigSpec)} 21 | } 22 | -------------------------------------------------------------------------------- /SetSyslog.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for adding syslogserver to hosts 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | # Setup common variables to use 6 | $vcenter = "vc.lab.local" 7 | $syslogservers = "udp://syslog.lab.local:514" 8 | 9 | Connect-VIServer -Server $vcenter 10 | 11 | # Setup variable to use in script for all hosts in vCenter 12 | $vmhosts = @(Get-VMHost) 13 | 14 | # Configure syslog on each host in vCenter 15 | foreach ($vmhost in $vmhosts) { 16 | Set-VMHostAdvancedConfiguration -Name Syslog.global.logHost -Value "$syslogservers" -VMHost $vmhost 17 | $esxcli = Get-EsxCli -VMHost $vmhost 18 | $esxcli.system.syslog.reload() 19 | } 20 | 21 | # Disconnect from vCenter 22 | Disconnect-VIServer * -Confirm:$false 23 | -------------------------------------------------------------------------------- /TEST.ps1: -------------------------------------------------------------------------------- 1 | #$vmList = Get-Cluster -Name "OMAEDC" | Get-VM 2 | $vm = Import-CSV "Z:\Documents\VMware\Scripts\CSVs\multiple-nics.csv" 3 | $vmList = Get-VM $vm.Name 4 | 5 | $x = 0 6 | 7 | foreach($vm in $vmList){ 8 | Write-Host $vm -Fore Green 9 | Get-NetworkAdapter -VM $vmList[$x] #| 10 | 11 | <# Below is testing. 12 | Select @{N="Name";Label="VM Name"}, 13 | @{Expression="Name";Label="NIC Name"}, 14 | @{Expression="NetworkName";E="VLAN"} | 15 | Export-CSV -NoTypeInformation -UseCulture "C:\vlan-report.csv" 16 | #Above is testing 17 | #> 18 | 19 | #Select {$_.Name} {$_.NetworkName} 20 | #Select Name, NetworkName 21 | Write-Host "" 22 | 23 | $x = $x + 1 24 | } #| 25 | #Export-CSV -NoTypeInformation -UseCulture "Z:\Documents\OUTPUT.csv" 26 | -------------------------------------------------------------------------------- /In Development/svMotionVMs.ps1: -------------------------------------------------------------------------------- 1 | Connect-VIServer -Server "DRSEDCAPP099" -User "ipgna\esb.service" -Password Password1 2 | Write-Host "`nConnected to vCenter Server: DRSEDCAPP099" 3 | 4 | #Get Guest machines from CSV file 5 | $vm = Get-View -ViewType VirtualMachine -Filter @{"Name" = "DRSEDCDNS100"} 6 | #hostView = Get-View -ID "$vm.Runtime.Host" 7 | #$hostView.Summary.Runtime 8 | #Write-Host $vm.Runtime.Host 9 | 10 | #import-csv "D:\Script_Repo\CSVs\svMotionVMs.csv" 11 | 12 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 13 | $extra = New-Object VMware.Vim.optionvalue 14 | $extra.Key="fsr.maxSwitchoverSeconds" 15 | $extra.Value="240" 16 | 17 | $vmConfigSpec.extraconfig += $extra 18 | 19 | #if ($vm -eq "DRSEDCMHT003") 20 | $vm.ReconfigVM($vmConfigSpec) 21 | # write-host -------------------------------------------------------------------------------- /Send-Email.ps1: -------------------------------------------------------------------------------- 1 | #Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File C:\pswd.txt 2 | # 3 | 4 | 5 | 6 | #$username = 'ipgna\robert.estes' 7 | 8 | #$password = #cat C:\pswd.txt | ConvertTo-SecureString 9 | 10 | #$cred = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $username, $password 11 | $cred = Get-Credential 12 | 13 | $param = @{ 14 | 15 | SmtpServer = 'relay-mail.interpublic.com' 16 | 17 | # Port = 587 18 | 19 | # UseSsl = $true 20 | 21 | Credential = $cred 22 | 23 | From = 'andru.estes@interpublic.com' 24 | 25 | To = 'andru.estes@interpublic.com' 26 | 27 | Subject = 'Testing' 28 | 29 | Body = "A sample email" 30 | 31 | # Attachments = 'C:\Temp\whatever.txt' 32 | 33 | } 34 | 35 | 36 | 37 | Send-MailMessage @param 38 | -------------------------------------------------------------------------------- /ExtendVMDKandGuest.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for adding vmdk to VM and extending disk in windows 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | param( 6 | [string]$VM 7 | ) 8 | $VM = Get-VM $VM 9 | Get-VM $VM|Get-HardDisk|FT Parent, Name, CapacityGB -Autosize 10 | $HardDisk = Read-Host "Enter VMware Hard Disk (Ex. 1)" 11 | $HardDisk = "Hard Disk " + $HardDisk 12 | $HardDiskSize = Read-Host "Enter the new Hard Disk size in GB (Ex. 50)" 13 | $VolumeLetter = Read-Host "Enter the volume letter (Ex. c,d,e,f)" 14 | Get-HardDisk -vm $VM | where {$_.Name -eq $HardDisk} | Set-HardDisk -CapacityGB $HardDiskSize -Confirm:$false 15 | Invoke-VMScript -vm $VM -ScriptText "echo rescan > c:\diskpart.txt && echo select vol $VolumeLetter >> c:\diskpart.txt && echo extend >> c:\diskpart.txt && diskpart.exe /s c:\diskpart.txt" -ScriptType BAT 16 | -------------------------------------------------------------------------------- /In Development/EnableSNMP.ps1: -------------------------------------------------------------------------------- 1 | #Enable and Configure SNMP Script v.1 2 | #This script enables SNMP on the hosts of a cluster and configure them with desired settings. 3 | # 4 | #Written by Zach Milleson 5 | # 6 | #v.1 10/29/2012 7 | 8 | 9 | #Prompt user for cluster 10 | $cluster = Read-Host "Enter Cluster" 11 | 12 | #Prompt user for vSwitch 13 | $vswitch = Read-Host "Enter vSwtich" 14 | 15 | #Prompt user for VLAN name 16 | $vlanname = Read-Host "Enter VLAN name" 17 | 18 | #Prompt user for VLAN ID 19 | $vlanid = Read-Host "Enter VLAN ID" 20 | 21 | #Gather hosts from vCenter for chosen cluster 22 | $MyVMHosts = Get-Cluster $cluster | Get-VMHost | sort Name | % {$_.Name} 23 | 24 | #Add VLAN IDs 25 | foreach ($hostname in $MyVMHosts) { 26 | Get-VirtualSwitch -VMHost $hostname -Name $vswitch | New-VirtualPortGroup -Name $vlanname -VLanId $vlanid 27 | } -------------------------------------------------------------------------------- /Unused-LUNS.ps1: -------------------------------------------------------------------------------- 1 | #: Author: Andru Estes 2 | #: December 09, 2015 3 | #: Script scans designated cluster for any LUNs that are presented but not being used by any VMs. Essentially orphaned LUNs. 4 | 5 | # Setting variables with user input. 6 | Write-Host "Enter cluster name: " -ForegroundColor Green -NoNewline 7 | $cluster = Read-Host 8 | 9 | # Gathering all ESXi Hosts. 10 | Write-Host "Gathering all ESXi hosts..." -ForegroundColor Magenta 11 | $esx = Get-Cluster $cluster | Get-VMHost 12 | 13 | <# Using the VMHosts within the chosen cluster, scanning for available LUNs that return a null value (not attached/used by VMs). 14 | Then, getting rid of duplicate LUN naa id's when presented to make it easier to read. 15 | #> 16 | $dsSys = Get-View $esx.Extensiondata.ConfigManager.DatastoreSystem 17 | $dsSys.QueryAvailableDisksForVmfs($null) | Select DisplayName, CanonicalName | Sort-Object -Property CanonicalName -Unique | FT -AutoSize -------------------------------------------------------------------------------- /Get-VMSnapshots.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for getting current VM snapshots 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | # Connect-VIserver your-vcenter-server -user your-user -password your-password 6 | 7 | param($Cluster) ## Input from command line 8 | 9 | if(!($Cluster)) 10 | { 11 | Write-Host -Fore YELLOW "Missing parameter!" 12 | Write-Host -Fore YELLOW "Usage:" 13 | Write-Host -Fore YELLOW ".\Get-VMSnapshots.ps1 " 14 | Write-Host -Fore YELLOW "" 15 | Write-Host -Fore YELLOW "Example: .\Get-VMSnapshots.ps1 LabCluster" 16 | exit 17 | } 18 | if(!(Get-Cluster $Cluster -EA SilentlyContinue)) 19 | { 20 | Write-Host -Fore RED "No cluster found with the name: $Cluster " 21 | Write-Host -Fore YELLOW "These clusters where found in the vCenter you have connected to:" 22 | Get-Cluster | sort Name | Select Name 23 | exit 24 | } 25 | Get-Cluster $Cluster|Get-VMHost|Get-VM|Get-Snapshot|Select VM, Name, Created|ft -a 26 | -------------------------------------------------------------------------------- /In Development/DoNotUpdateVMtoInstallToolsonReboot.ps1: -------------------------------------------------------------------------------- 1 | #Turn OFF Automatic Install of Tools on Reboot Script v.1 2 | #This script turns OFF the feature to install a new version of the VMware tools when a Windows host reboots. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 03/27/2012 7 | 8 | #Prompt for Datacenter and Cluster 9 | $datacenter = Read-Host "Enter Datacenter" 10 | 11 | #Get Windows Guest machines in cluster from vCenter server 12 | $vmguests = Get-Datacenter $datacenter | Get-VM | %{Get-View $_.ID} | where {$_.Guest.GuestFamily -match "windowsGuest"} 13 | 14 | #Create new Virtual Machince Config Spec 15 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 16 | 17 | #Write new config options to VMs 18 | foreach ($vm in $vmguests){ 19 | 20 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 21 | $vmConfigSpec.tools = New-Object VMware.Vim.ToolsConfigInfo 22 | $vmConfigSpec.tools.toolsUpgradePolicy = "manual" 23 | 24 | $vm.ReconfigVM_Task($vmConfigSpec) 25 | } 26 | -------------------------------------------------------------------------------- /Get-VM-IP-VLAN.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes (with help of VMware community) 2 | #: November 12, 2015 3 | #: Script reads in cs of VMs with multiple NICs, takes that list and exports the IP and VLAN for the NICs. 4 | 5 | # Importing CSV with VMs to use. 6 | $vmList = Import-CSV "Z:\Documents\VMware\Scripts\CSVs\multiple-nics.csv" 7 | 8 | # Setting the target lsit to use for processing info. 9 | $targetVMs = $vmList.name 10 | 11 | Get-VM $targetVMs | 12 | ForEach-Object { 13 | $VM = $_ 14 | $VM | Get-VMGuest | Select-Object -ExpandProperty Nics | 15 | ForEach-Object { 16 | $Nic = $_ 17 | foreach ($IP in $Nic.IPAddress) 18 | { 19 | if ($IP.Contains('.')) 20 | { 21 | "" | Select-Object -Property @{Name='VM';Expression={$VM.Name}}, 22 | @{Name='IPAddress';Expression={$IP}}, 23 | @{Name='NetworkName';Expression={$Nic.NetworkName}} 24 | } 25 | } 26 | } 27 | } | 28 | Export-CSV -NoTypeInformation -UseCulture "Z:\Documents\VMware\Scripts\CSVs\OUTPUT.csv" 29 | 30 | -------------------------------------------------------------------------------- /Get-HostiSCSIIQN.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for getting the Software iSCSI IQNs 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | # Connect-VIserver your-vcenter-server -user your-user -password your-password 6 | 7 | param($Cluster) ## Input from command line 8 | 9 | if(!($Cluster)) 10 | { 11 | Write-Host -Fore YELLOW "Missing parameter!" 12 | Write-Host -Fore YELLOW "Usage:" 13 | Write-Host -Fore YELLOW ".\Get-HostiSCSIIQN.ps1 " 14 | Write-Host -Fore YELLOW "" 15 | Write-Host -Fore YELLOW "Example: .\Get-HostiSCSIIQN.ps1 LabCluster" 16 | exit 17 | } 18 | if(!(Get-Cluster $Cluster -EA SilentlyContinue)) 19 | { 20 | Write-Host -Fore RED "No cluster found with the name: $Cluster " 21 | Write-Host -Fore YELLOW "These clusters where found in the vCenter you have connected to:" 22 | Get-Cluster | sort Name | Select Name 23 | exit 24 | } 25 | Get-Cluster $Cluster|Get-VMHost|get-VMHostHBA -Type iScsi | Where {$_.Model -eq "iSCSI Software Adapter"}| Select VMhost, IScsiname|Sort-Object VMHost | ft -a 26 | -------------------------------------------------------------------------------- /Cluster-Get-VM-Information.ps1: -------------------------------------------------------------------------------- 1 | Get-Cluster | Select Name | Export-Csv C:\cl.txt -NoTypeInformation -UseCulture 2 | 3 | Import-Csv C:\cl.txt -UseCulture | %{ 4 | $cl=$_.Name 5 | Get-VM -Location (Get-Cluster -Name $cl) | 6 | Select-Object @{N="Cluster";E={$cl}}, 7 | @{Expression="VMHost"; Label="ESXi Host"}, 8 | @{Expression="Name"; Label="VM"}, 9 | @{Expression="Numcpu"; Label="vCPU"}, 10 | @{Expression="MemoryGB"; Label="RAM(GB)"}, 11 | @{ n="Volume provisionne"; e={[math]::round( $_.ProvisionedSpaceGB, 2 )}}, 12 | @{ n="Volume utilise"; e={[math]::round( $_.UsedSpaceGB, 2 )}} | 13 | # @{N="IOPS/Ecriture"; E={[math]::round((Get-Stat $_ -stat "datastore.numberWriteAveraged.average" -RealTime | Select -Expand Value | measure -average).Average, 1)}}, 14 | # @{N="IOPS/Lecture"; E={[math]::round((Get-Stat $_ -stat "datastore.numberReadAveraged.average" -RealTime | Select -Expand Value | measure -average).Average, 1)}} | 15 | Export-Csv -NoTypeInformation -UseCulture "C:\vm_report_$($cl).csv" 16 | } -------------------------------------------------------------------------------- /In Development/AddVLANids.ps1: -------------------------------------------------------------------------------- 1 | #vSwitch Creation Script v.1 2 | #This script creates a new vSwitch on every host in the cluster. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 7/7/2011 7 | 8 | #Prompt user for vCenter server and connect. 9 | #$vcenter = Read-Host "Enter vCenter Server" 10 | Connect-VIServer -Server "drsedcapp099" -User "ipgna\esb.service" -Password Password1 11 | Write-Host "`nConnected to vCenter Server: DRSEDCAPP099" 12 | 13 | #Prompt user for datacenter and cluster 14 | #$datacenter = Read-Host "Enter Datacenter" 15 | #$cluster = Read-Host "`Enter Cluster" 16 | 17 | #Gather hosts from vCenter for chosen cluster 18 | Write-Host "Getting hosts from cluster..." 19 | $MyVMHosts = Get-Datacenter "DRSEDC" | Get-Cluster "DRSEDC" | Get-VMHost 20 | 21 | #Add VLAN IDs 22 | foreach ($hostname in $MyVMHosts) { 23 | #Get-VirtualSwitch -Name "vSwitch0" | Get-VirtualPortGroup -Name "vMotion" | Set-VirtualPortGroup -VLanId "421" -Confirm:$false 24 | Get-VirtualSwitch -Name "vSwitch0" | Get-VirtualPortGroup -Name "FT Logging" | Set-VirtualPortGroup -VLanId "422" -Confirm:$false 25 | 26 | Write-Host "$hostname...done." 27 | } -------------------------------------------------------------------------------- /Get-Host-NICs.ps1: -------------------------------------------------------------------------------- 1 | # The following example lists all hosts nics and nic speeds 2 | 3 | #Connect-VIServer MYVISERVER 4 | 5 | Write "Gathering VMHost objects" 6 | $vmhosts = Get-VMHost | Sort Name | Where-Object {$_.State -eq "Connected"} | Get-View 7 | $Information = @() 8 | foreach ($vmhost in $vmhosts){ 9 | $ESXHost = $vmhost.Name 10 | Write "Collating information for $ESXHost" 11 | $networkSystem = Get-view 12 | $vmhost.ConfigManager.NetworkSystem 13 | foreach($pnic in $networkSystem.NetworkConfig.Pnic){ 14 | $pnicInfo = $networkSystem.QueryNetworkHint($pnic.Device) 15 | foreach($Hint in $pnicInfo){ 16 | $NetworkInfo = "" | select-Object Host, PNic, Speed 17 | $NetworkInfo.Host = $vmhost.Name 18 | $NetworkInfo.PNic = $Hint.Device 19 | $record = 0 20 | Do { 21 | If ($Hint.Device -eq $vmhost.Config.Network.Pnic[$record].Device){ 22 | $NetworkInfo.Speed = $vmhost.Config.Network.Pnic[$record].LinkSpeed.SpeedMb 23 | } 24 | $record ++ 25 | } 26 | Until ($record -eq ($vmhost.Config.Network.Pnic.Length)) 27 | $Information += $NetworkInfo 28 | } 29 | } 30 | } 31 | $Information | Sort Host, PNic -------------------------------------------------------------------------------- /In Development/UpdateVMtoInstallToolsonReboot.ps1: -------------------------------------------------------------------------------- 1 | #Turn on Automatic Install of Tools on Reboot Script v.1 2 | #This script turns on the feature to install a new version of the VMware tools when a Windows host reboots. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 10/7/2011 7 | 8 | #Prompt for Datacenter and Cluster 9 | #$datacenter = Read-Host "`nEnter Datacenter: " 10 | #$cluster = Read-Host "Enter Cluster: " 11 | 12 | #Get Windows Guest machines in cluster from vCenter server 13 | $vmguests = Get-Datacenter OMAEDC | Get-VM | %{Get-View $_.ID} | where {$_.Guest.GuestFamily -match "windowsGuest"} 14 | 15 | #Get Guest machines from CSV file 16 | #$vmguests = import-csv "D:\Script_Repo\CSVs\_.csv" 17 | 18 | #Create new Virtual Machince Config Spec 19 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 20 | 21 | #Write new config options to VMs using csv 22 | foreach ($vm in $vmguests){ 23 | 24 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 25 | $vmConfigSpec.tools = New-Object VMware.Vim.ToolsConfigInfo 26 | $vmConfigSpec.tools.toolsUpgradePolicy = "upgradeAtPowerCycle" 27 | 28 | $vm.ReconfigVM_Task($vmConfigSpec) 29 | } 30 | -------------------------------------------------------------------------------- /Propogate-vSwitch-Settings.ps1: -------------------------------------------------------------------------------- 1 | # Author: Virtual-Al w/ edits by Andru Estes 2 | # Script: Copies existing vSwitch and PortGroup configurations and propogates them to a newly installed ESXi host. 3 | 4 | 5 | #$VISRV = Connect-VIServer (Read-Host "Please enter the name of your VI SERVER") 6 | $BASEHost = Get-VMHost -Name (Read-Host "Please enter the name of your existing server as seen in the VI Client:") 7 | $NEWHost = Get-VMHost -Name (Read-Host "Please enter the name of the server to configure as seen in the VI Client:") 8 | 9 | $BASEHost | Get-VirtualSwitch -Standard | Foreach { 10 | If (($NEWHost | Get-VirtualSwitch -Standard -Name $_.Name-ErrorAction SilentlyContinue)-eq $null){ 11 | Write-Host "Creating Virtual Switch $($_.Name)" 12 | $NewSwitch = $NEWHost | New-VirtualSwitch -Name $_.Name-NumPorts $_.NumPorts-Mtu $_.Mtu 13 | $vSwitch = $_ 14 | } 15 | $_ | Get-VirtualPortGroup -Standard | Foreach { 16 | If (($NEWHost | Get-VirtualPortGroup -Standard -Name $_.Name-ErrorAction SilentlyContinue)-eq $null){ 17 | Write-Host "Creating Portgroup $($_.Name)" 18 | $NewPortGroup = $NEWHost | Get-VirtualSwitch -Standard -Name $vSwitch | New-VirtualPortGroup -Name $_.Name-VLanId $_.VLanID 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /In Development/CreatevSwitch.ps1: -------------------------------------------------------------------------------- 1 | #vSwitch Creation Script v.1 2 | #This script creates a new vSwitch on every host in the cluster. 3 | # 4 | #Written by Eric Tekrony 5 | #Edited by Andru Estes 6 | # 7 | #v.1 7/7/2011 8 | #v.2 11/02/2015 9 | 10 | #Prompt user for datacenter and cluster 11 | $datacenter = Read-Host "Enter Datacenter" 12 | $cluster = Read-Host "`Enter Cluster" 13 | 14 | #Gather hosts from vCenter for chosen cluster 15 | Write-Host "Getting hosts from cluster..." 16 | $MyVMHosts = Get-Datacenter $datacenter | Get-Cluster $cluster | Get-VMHost 17 | 18 | #Prompt user for vSwitch name 19 | $vswitchname = Read-Host "Enter name of new vSwitch" 20 | 21 | #DEPRECATED!! Prompt user for number of ports 22 | #$ports = Read-Host "Enter number of ports for vSwitch" 23 | 24 | #Prompt user for nics to connect 25 | $vmNICS = Get-VMHostNetworkAdapter -VMHost $myVMHosts | % {$_.Name} 26 | #$nicstring = Read-Host "Enter names of NICs to connect (example: vmnic1,vmnic2)" 27 | 28 | #Get Guest machines from CSV file 29 | #$MyVMHosts = import-csv "D:\Script_Repo\CSVs\createvswitch.csv" 30 | 31 | #Create new vSwitch on each host. 32 | foreach ($hostname in $MyVMHosts) { 33 | New-VirtualSwitch -VMHost $hostname -Name $vswitchname 34 | 35 | Write-Host "$hostname...done." 36 | } -------------------------------------------------------------------------------- /Get-Datacenter-VMs_Info.ps1: -------------------------------------------------------------------------------- 1 | #: Author: Andru Estes (with PowerCLI community help) 2 | #: Date: November 03, 2015 3 | #: Use: Takes user input for chosen datacenter and creates a VM report calculating VM Name, Datastore location, Provisioned/Used Space, and Folder. 4 | 5 | 6 | # Seting the datacenter by using the specific DataCenter name. 7 | "" 8 | $dataCenter = Read-Host "Please enter the datacenter choice (OMA, CHI, LDN)" 9 | 10 | #Check the user entered a valid dataCenter choice. If not, it breaks them out of the script;. 11 | if($dataCenter -eq "OMA" -or $dataCenter -eq "CHI" -or $dataCenter -eq "LDN"){ 12 | Write-Host " " 13 | Write-Host "Creating CSV report under C:\ ..." 14 | 15 | Get-Datacenter -Name $dataCenter | 16 | Get-VM | 17 | Select Name, 18 | @{N="Datastore";E={[string]::Join(',',(Get-Datastore -Id $_.DatastoreIdList | Select -ExpandProperty Name))}}, 19 | @{N="UsedSpaceGB";E={[math]::Round($_.UsedSpaceGB,1)}}, 20 | @{N="ProvisionedSpaceGB";E={[math]::Round($_.ProvisionedSpaceGB,1)}}, 21 | @{N="Folder";E={$_.Folder.Name}} | 22 | Export-Csv C:\${dataCenter}-vm-report.csv -NoTypeInformation -UseCulture 23 | } 24 | else{ 25 | "Sorry, that is not a valid option. Please try the script again..." 26 | "The three options are: OMA, CHI, LDN" 27 | "" 28 | } 29 | -------------------------------------------------------------------------------- /RDM-Listing.ps1: -------------------------------------------------------------------------------- 1 | $report = @() 2 | $rdmVMs = @() 3 | $vms = Get-VM | Get-View 4 | 5 | foreach($machine in $vms){ 6 | foreach($dev in $machine.Config.Hardware.Device){ 7 | if(($dev.gettype()).Name -eq "VirtualDisk"){ 8 | if(($dev.Backing.CompatibilityMode -eq "physicalMode") -or 9 | ($dev.Backing.CompatibilityMode -eq "virtualMode")){ 10 | $row = "" | select VMName, VMHost, LUNName 11 | $row.VMName = $machine.Name 12 | $esx = Get-View $machine.Runtime.Host 13 | $row.VMHost = ($esx).Name 14 | # $row.HDDeviceName = $dev.Backing.DeviceName 15 | # $row.HDFileName = $dev.Backing.FileName 16 | # $row.HDMode = $dev.Backing.CompatibilityMode 17 | # $row.HDSize = $dev.CapacityInKB 18 | $row.LUNName = ($esx.Config.StorageDevice.ScsiLun | where {$_.Uuid -eq $dev.Backing.LunUuid}).DisplayName 19 | # $report += $row 20 | $rdmVMs += @($row | Select-Object -Property VMName, LUNName, VMHost) 21 | } 22 | } 23 | } 24 | } 25 | #$report #| Export-Csv -NoTypeInformation C:\RDM-Report.csv 26 | 27 | $rdmVMs | FT -AutoSize 28 | @($rdmVMs.Count) 29 | -------------------------------------------------------------------------------- /In Development/EnableFTLogging.ps1: -------------------------------------------------------------------------------- 1 | #vSphere Enable FT Logging Script v.1 2 | #This enables Fault Tolerance Logging on the existing vMotion port on all ESX hosts in datacenter. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 6/21/2011 7 | 8 | #Prompt user for vCenter server and connect. 9 | #$vcenter = Read-Host "Enter vCenter Server" 10 | #Connect-VIServer -Server $vcenter -User "ipgna\esb.service" -Password Password1 11 | #Write-Host "`nConnected to vCenter Server: $vcenter" 12 | 13 | #Prompt user for datacenter and cluster 14 | $datacenter = Read-Host "`nEnter Datacenter" 15 | $cluster = Read-Host "`nEnter Cluster" 16 | 17 | #Gather hosts from vCenter for chosen cluster 18 | Write-Host "`nGetting hosts from cluster..." 19 | $MyVMHosts = Get-Datacenter $datacenter | Get-Cluster $cluster | Get-VMHost 20 | 21 | #Get Guest machines from CSV file 22 | #$MyVMHosts = import-csv "D:\Script_Repo\CSVs\HostFTLogging.csv" 23 | 24 | #Connect to each host and enable FT Logging. 25 | foreach ($hostname in $MyVMHosts) { 26 | 27 | $hostView = Get-VMHost $hostname | Get-View -Property configManager 28 | $nicManager = Get-View $hostView.configManager.virtualNicManager 29 | $nicManager.SelectVnicForNicType("faultToleranceLogging", "vmk0") 30 | 31 | Disconnect-VIServer -Confirm:$false 32 | Write-Host "`n$hostname...done." 33 | } -------------------------------------------------------------------------------- /Create-Snapshot.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes 2 | #: November 2015 3 | 4 | # Create a new snapshot of a desired VM. 5 | # Script defaults are: Quiescing filesystem = True || Memory snapshot = False. 6 | 7 | Write-Host "" 8 | Write-Host "Checking if connected to vCenter..." -Foreground "Yellow" 9 | 10 | 11 | if ($Global:DefaultVIServers.count -eq 0){ 12 | Write-Host "You are not connected, connecting now..." -Foreground "Yellow" 13 | Write-Host "" 14 | # Setting desired vCenter, user name, and secured password. 15 | $viServer = Read-Host "Enter vCenter Server" 16 | $user = Read-Host "Enter user name" 17 | $securePassword = Read-Host -Prompt "Enter password" -AsSecureString 18 | 19 | # Extracting the secured password to pass into automated script as plain text. 20 | $BSTR = ` 21 | [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword) 22 | $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 23 | 24 | Connect-VIServer -Server $viServer -User $user -Password $PlainPassword 25 | } 26 | else{ 27 | Write-Host "" 28 | Write-Host "You are already connected to vCenter, proceeding..." -Foreground "Yellow" 29 | } 30 | 31 | Write-Host "" 32 | 33 | $snapshotName = Read-Host "Enter snapshot name" 34 | $vm = Read-Host "Enter the target VM" 35 | $description = Read-Host "Enter description" 36 | 37 | New-Snapshot -Name $snapshotName -VM $vm -Description $description -Memory:$false -Quiesce:$true 38 | -------------------------------------------------------------------------------- /In Development/DetachSCSILUN.ps1: -------------------------------------------------------------------------------- 1 | # Script to Detach a SCSI LUN by name from all hosts in cluster 2 | # by: Eric TeKrony 3 | # 4 | # v.1 -- 3/28/2012 5 | 6 | function Detach-Disk{ 7 | param([VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost,[string]$CanonicalName) 8 | 9 | $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem 10 | $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid 11 | 12 | $storSys.DetachScsiLun($lunUuid) 13 | } 14 | 15 | #function Attach-Disk{ 16 | # param( 17 | # [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost, 18 | # [string]$CanonicalName ) 19 | # 20 | # $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem 21 | # $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid 22 | # 23 | # $storSys.AttachScsiLun($lunUuid) 24 | #} 25 | 26 | # Ask for cluster 27 | $cluster = Read-Host "Which cluster" 28 | 29 | # Ask user for LUN Name 30 | $name = Read-Host "What is the LUN Name you wish to detach" 31 | 32 | # Gather all hosts from cluster 33 | $MyVMHosts = Get-Cluster $cluster | Get-VMHost | sort Name | % {$_.Name} 34 | 35 | # Run detach command on all hosts in cluster 36 | foreach ($hostname in $MyVMHosts) { 37 | $myhost = Get-VMHost $hostname 38 | Detach-Disk -VMHost $myhost -CanonicalName $name 39 | } 40 | 41 | -------------------------------------------------------------------------------- /AddVLANID.ps1: -------------------------------------------------------------------------------- 1 | #vSwitch Creation Script v.1 2 | #This script creates a new vSwitch on every host in the cluster. 3 | # 4 | #Written by Eric Tekrony 5 | #Edited by Andru Estes 6 | # 7 | #v.1 7/7/2011 8 | #v.2 11/02/2015 9 | 10 | 11 | #Prompt user for cluster 12 | $cluster = Read-Host "Enter Cluster" 13 | 14 | #Prompt user for vSwitch 15 | $vswitch = Read-Host "Enter vSwitch" 16 | 17 | #Reading CSV file for autopopulation of VLANs. 18 | $vlanCSV = Import-Csv "Z:\Documents\VMware\Scripts\CSVs\vlans.csv" 19 | 20 | #Gather hosts from vCenter for chosen cluster 21 | $MyVMHosts = Get-Cluster $cluster | Get-VMHost | sort Name | % {$_.Name} 22 | 23 | #Prompting for user choice 24 | $selection = Read-Host "Would you like to specify the VLANs? If so, type YES, otherwise type NO" 25 | 26 | #Add all VLAN IDs if desired. 27 | if ($selection -eq "N" -or $selection -eq "NO"){ 28 | foreach ($hostname in $MyVMHosts) { 29 | foreach ($newVlan in $vlanCSV) { 30 | Get-VirtualSwitch -VMHost $hostname -Name $vswitch | New-VirtualPortGroup -Name $newVlan.name -VLanId $newVlan.vlanid 31 | } 32 | } 33 | } 34 | 35 | elseif ($selection -eq "Y" -or $selection -eq "YES"){ 36 | #Prompt user for VLAN name 37 | $vlanname = Read-Host "Enter VLAN name" 38 | 39 | #Prompt user for VLAN ID 40 | $vlanid = Read-Host "Enter VLAN ID" 41 | 42 | foreach ($hostname in $MyVMHosts) { 43 | Get-VirtualSwitch -VMHost $hostname -Name $vswitch | New-VirtualPortGroup -Name $vlanname -VLanId $vlanid 44 | } 45 | } -------------------------------------------------------------------------------- /Attach-SCSILun.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes (w/ LucD help) 2 | #: December 09, 2015 3 | #: Script reads in user input of NAA ID for desired LUN and automates the process of attaching to a cluster. 4 | 5 | # Settings... 6 | # Entering the LUN naa Id. 7 | $LunIds = Read-Host "Enter NAA ID here" 8 | 9 | # Setting the desired cluster with user input. 10 | $Clustername = Read-Host "Enter Cluster name" 11 | 12 | ####################################################### 13 | ### Initializing Functions ### 14 | ####################################################### 15 | 16 | function Attach-Disk{ 17 | param( 18 | [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost, 19 | [string]$CanonicalName 20 | ) 21 | 22 | $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem 23 | $lunUuid = (Get-ScsiLun -VmHost $VMHost | 24 | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid 25 | 26 | $storSys.AttachScsiLun($lunUuid) 27 | } 28 | 29 | ####################################################### 30 | ### End of Initialization ### 31 | ####################################################### 32 | 33 | # Collecting all ESXi hosts within the selected cluster. 34 | Write-Host "Gathering ESXi hosts..." -ForegroundColor Magenta 35 | $ClusterHosts = Get-Cluster $Clustername | Get-VMHost 36 | 37 | # For every ESXi host within the cluster, and for every LUN ID within the LUN IDs entered, detach that LUN from each host using NAA ID and loop for all hosts. 38 | Foreach($VMHost in $ClusterHosts) 39 | { 40 | Foreach($LUNid in $LunIDs) 41 | { 42 | Write-Host "Attaching" $LUNid "onto" $VMHost -ForegroundColor "Yellow" 43 | Attach-Disk -VMHost $VMHost -CanonicalName $LUNid 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /CloneVMs.ps1: -------------------------------------------------------------------------------- 1 | # PowerCLI Script for cloning VMs and customizing disk, cpu and memory 2 | # @davidstamen 3 | # http://davidstamen.com 4 | 5 | $vmlist = Import-CSV '.\VMs.csv' 6 | 7 | foreach ($item in $vmlist) { 8 | $basevm = $item.basevm 9 | $datastore = $item.datastore 10 | $vmcluster = $item.vmcluster 11 | $custspec = $item.custspec 12 | $vmname = $item.vmname 13 | $ipaddr = $item.ipaddress 14 | $subnet = $item.subnet 15 | $gateway = $item.gateway 16 | $pdns = $item.pdns 17 | $sdns = $item.sdns 18 | $vlan = $item.vlan 19 | $sdisk = $item.sdisk 20 | $folder = $item.folder 21 | $totalcpu = $item.totalcpu 22 | $corespersocket = $item.corespersocket 23 | $memorygb = $item.memorygb 24 | 25 | #Get the Specification and set the Nic Mapping 26 | Get-OSCustomizationSpec $custspec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $ipaddr -SubnetMask $subnet -DefaultGateway $gateway -Dns $pdns,$sdns 27 | 28 | #Clone the BaseVM with the adjusted Customization Specification 29 | New-VM -Name $vmname -Location $folder -VM $basevm -Datastore $datastore -ResourcePool $vmcluster -OSCustomizationSpec $custspec 30 | Get-NetworkAdapter -VM $vmname|Set-NetworkAdapter -NetworkName $vlan -confirm:$false 31 | #Add second disk if one is listed 32 | if ($sdisk -gt "1") { 33 | New-HardDisk -vm $vmname -CapacityGB $sdisk -Datastore $datastore -StorageFormat "EagerZeroedThick" 34 | } 35 | #adjust number of cpu's and sockets 36 | $spec = new-object -typename VMware.VIM.virtualmachineconfigspec -property @{'numcorespersocket'=$corespersocket;'numCPUs'=$totalcpu} 37 | (Get-VM $vmname).ExtensionData.ReconfigVM_Task($spec) 38 | 39 | #adjust memory allocation 40 | Set-VM -VM $vmname -MemoryGB $memorygb -confirm:$false 41 | } 42 | -------------------------------------------------------------------------------- /In Development/Query_vRAM.ps1: -------------------------------------------------------------------------------- 1 | Connect-VIServer -Server 144.210.224.5 -User "ipgna\esb.service" -Password "Password1" 2 | 3 | function Get-vRAMInfo{ 4 | $vRAMtab = @{ 5 | "esxEssentials"=24; 6 | "esxEssentialsPlus"=24; 7 | "esxStandard"=24; 8 | "esxAdvanced"=32; 9 | "esxEnterprise"=32; 10 | "esxEnterprisePlus"=48 11 | } 12 | 13 | $licMgr = Get-View LicenseManager 14 | $licAssignMgr = Get-View $licMgr.LicenseAssignmentManager 15 | 16 | $totals = @{} 17 | 18 | Get-VMHost | %{ 19 | $lic = $licAssignMgr.QueryAssignedLicenses($_.Extensiondata.MoRef.Value) 20 | $licType = $lic[0].AssignedLicense.EditionKey 21 | $totalvRAM = ($vRAMtab[$licType] * $_.Extensiondata.Hardware.CpuInfo.NumCpuPackages) 22 | 23 | $VMs = Get-VM -Location $_ 24 | $vmRAMConfigured = ($VMs | Measure-Object -Property MemoryMB -Sum).Sum/1KB 25 | $vmRAMUsed = ($VMs | where {$_.PowerState -eq "PoweredOn"} | Measure-Object -Property MemoryMB -Sum).Sum/1KB 26 | 27 | if($totals.ContainsKey($licType)){ 28 | $totals[$licType].vRAMEntitled += $totalvRAM 29 | $totals[$licType].vRAMConfigured += $vmRAMConfigured 30 | $totals[$licType].vRAMUsed += $vmRAMUsed 31 | } 32 | else{ 33 | $totals[$licType] = New-Object PSObject -Property @{ 34 | vCenter = $defaultVIServer.Name 35 | LicenseType = $lic[0].AssignedLicense.Name 36 | vRAMEntitled = $totalvRAM 37 | vRAMConfigured = $vmRAMConfigured 38 | vRAMUsed = $vmRAMUsed 39 | } 40 | } 41 | } 42 | $totals.GetEnumerator() | %{ 43 | New-Object PSObject -Property @{ 44 | vCenter = $_.Value.vCenter 45 | LicenseType = $_.Value.LicenseType 46 | vRAMEntitled = $_.Value.vRAMEntitled 47 | vRAMConfigured = [Math]::Round($_.Value.vRAMConfigured,1) 48 | vRAMUsed = [Math]::Round($_.Value.vRAMUsed,1) 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Detach-SCSILun.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes (w/ LucD help) 2 | #: December 04, 2015 3 | #: Script takes in chosen LUN using the NAA ID and automates the process of detaching the datastore/RDM from every host in the cluster. 4 | 5 | 6 | # Setting the selected NAA ID using user input. One at a time via input. 7 | # Can enter multiple NAA IDs at once that are comma separated like below. 8 | # Uncomment line below to do so, make sure to comment out the original line with 'Read-Host'before proceeding. 9 | #$LunIDs = "naa.50002ac003cd0dbb", "naa.50002ac003cb0dbb" 10 | $LunIDs = Read-Host "Enter NAA ID here" 11 | 12 | # Setting the desired cluster with user input. 13 | $Clustername = Read-Host "Enter Cluster name" 14 | 15 | 16 | ####################################################### 17 | ### Initializing Functions ### 18 | ####################################################### 19 | 20 | function Detach-Disk{ 21 | param( 22 | [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHost, 23 | [string]$CanonicalName ) 24 | 25 | $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem 26 | $lunUuid = (Get-ScsiLun -VmHost $VMHost | where {$_.CanonicalName -eq $CanonicalName}).ExtensionData.Uuid 27 | 28 | $storSys.DetachScsiLun($lunUuid) 29 | } 30 | 31 | ####################################################### 32 | ### End of Initialization ### 33 | ####################################################### 34 | 35 | # Collecting all ESXi hosts within the selected cluster. 36 | Write-Host "Gathering ESXi hosts..." -ForegroundColor Magenta 37 | $ClusterHosts = Get-Cluster $Clustername | Get-VMHost 38 | 39 | # For every ESXi host within the cluster, and for every LUN ID within the LUN IDs entered, detach that LUN from each host using NAA ID and loop for all hosts. 40 | Foreach($VMHost in $ClusterHosts) 41 | { 42 | Foreach($LUNid in $LunIDs) 43 | { 44 | Write-Host "Detaching" $LUNid "from" $VMHost -ForegroundColor "Yellow" 45 | Detach-Disk -VMHost $VMHost -CanonicalName $LUNid 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /In Development/ChangeDRSVLANs.ps1: -------------------------------------------------------------------------------- 1 | #vSphere PortGroup Reconfigure -- DRS v.1 2 | #This script will add the new VLAN IDs, change the VMs to the new ones, then delete the old ones in the cluster. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 7/13/2011 7 | #v.2 11/02/2015 - Edited by Andru Estes 8 | 9 | #Prompt user for vCenter server and connect. 10 | #$vcenter = Read-Host "Enter vCenter Server" 11 | #Connect-VIServer -Server $vcenter -User "ipgna\esb.service" -Password Password1 12 | #Write-Host "`nConnected to vCenter Server: $vcenter" 13 | 14 | #Prompt user for datacenter and cluster 15 | $datacenter = Read-Host "`nEnter Datacenter" 16 | $cluster = Read-Host "`nEnter Cluster" 17 | 18 | #Gather hosts from vCenter for chosen cluster 19 | Write-Host "`nGetting hosts from cluster..." 20 | $MyVMHosts = Get-Datacenter $datacenter | Get-Cluster $cluster | Get-VMHost 21 | 22 | #Get Guest machines from CSV file 23 | #$MyVMHosts = import-csv "D:\Script_Repo\CSVs\DRSHosts.csv" 24 | 25 | #Gather VM machines from Cluster 26 | $MyVMs = Get-Datacenter $datacenter | Get-Cluster $cluster | Get-VM 27 | 28 | #Get New VLAN IDs 29 | $NewVlanIds = Import-Csv "D:\Script_Repo\CSVs\NewDRSVLANs.csv" 30 | 31 | #Add new VLANs to hosts 32 | foreach ($hostname in $MyVMHosts) { 33 | foreach ($newvlan in $NewVlanIds) { 34 | New-VirtualPortGroup -VirtualSwitch "vSwitch0" -Name $newvlan.newname -VLanId $newvlan.newid -Confirm $false 35 | } 36 | Write-Host "`n$hostname...created new VLANs." 37 | } 38 | 39 | #Reconfigure each VM to new VLANS 40 | foreach ($vm in $MyVMs) { 41 | $vmnics = Get-NetworkAdapter -VM $vm 42 | 43 | foreach ($nic in $vmnics) { 44 | 45 | foreach ($newvlan in $NewVlanIds) { 46 | if ($nic.NetworkName -eq $newvlan.oldname) { 47 | Set-NetworkAdapter -NetworkName $newvlan.newname 48 | } 49 | } 50 | } 51 | 52 | Write-Host "`n$vm...done." 53 | } 54 | 55 | #Remove old VLANs from hosts 56 | foreach ($hostname in $MyVMHosts) { 57 | foreach ($newvlan in $NewVlanIds) { 58 | Get-VirtualSwitch -Name "vSwitch0" | Remove-VirtualPortGroup -VirtualPortGroup $newvlan.oldname 59 | } 60 | Write-Host "`n$hostname...removed old VLANs." 61 | } 62 | -------------------------------------------------------------------------------- /In Development/ConfigDRvSwitch0.ps1: -------------------------------------------------------------------------------- 1 | #Prompt user for vCenter server and connect. 2 | #$vcenter = Read-Host "Enter vCenter Server" 3 | Connect-VIServer -Server "DRSEDCAPP099" -User "ipgna\esb.service" -Password Password1 4 | Write-Host "`nConnected to vCenter Server: $vcenter" 5 | 6 | #Gather hosts from vCenter for chosen cluster 7 | Write-Host "`nGetting hosts from cluster..." 8 | $MyVMHosts = Get-Datacenter "DRSEDC" | Get-Cluster "DRSEDC4i" | Get-VMHost 9 | 10 | #Get Guest machines from CSV file 11 | #$MyVMHosts = import-csv "D:\Script_Repo\CSVs\NewDRHosts.csv" 12 | 13 | #Connect to each host, create 2 new port groups, enable vMotion on one, and FT Logging on the the other. 14 | foreach ($hostname in $MyVMHosts) { 15 | # $vip = $MyVMHosts.vip 16 | # $ftip = $MyVMHosts.ftip 17 | 18 | Connect-VIServer -Server $hostname -User "root" -Password H0me*Brew3r 19 | Write-Host "`nConnected to $hostname" 20 | 21 | # Get-VMHost | Get-VMHostNetworkAdapter -VMKernel | Set-VMHostNetworkAdapter -VMotionEnabled $false -Confirm:$false 22 | # $network = Get-VMHostNetwork 23 | # Remove-VMHostNetworkAdapter $network.VirtualNic[0] -Confirm:$false 24 | # Remove-VirtualSwitch -VirtualSwitch "vSwitch3" -Confirm:$false 25 | # New-VMHostNetworkAdapter -PortGroup "vMotion" -VirtualSwitch "vSwitch0" -IP $vip -SubnetMask 255.255.255.192 -VMotionEnabled:$true 26 | # New-VMHostNetworkAdapter -PortGroup "FT Logging" -VirtualSwitch "vSwitch0" -IP $ftip -SubnetMask 255.255.255.192 -FaultToleranceLoggingEnabled:$true 27 | # New-VirtualSwitch -NumPorts 64 -Name "vSwitch3" -Nic "vmnic4" 28 | # New-VirtualPortGroup -Name "10.199.37.0_27_VLAN.126" -VLanId "126" -VirtualSwitch "vSwitch3" 29 | # Set-VirtualSwitch -VirtualSwitch "vSwitch0" -NumPorts 16 -Confirm:$false 30 | # Get-VMHost | Get-VMHostNetwork | Set-VMHostNetwork -VMKernelGateway 144.210.207.65 31 | 32 | 33 | Set-VirtualSwitch -VirtualSwitch "vSwitch1" -Nic "vmnic1" -Confirm:$false 34 | Set-VirtualSwitch -VirtualSwitch "vSwitch2" -Nic "vmnic2" -Confirm:$false 35 | Set-VirtualSwitch -VirtualSwitch "vSwitch3" -Nic "vmnic3" -Confirm:$false 36 | 37 | Disconnect-VIServer -Confirm:$false 38 | Write-Host "`n$hostname...done." 39 | } -------------------------------------------------------------------------------- /In Development/CopyvSwitchFromHosttoHost.ps1: -------------------------------------------------------------------------------- 1 | #Copy vSwitch from Host to Host v.1 2 | #This script will clone a vSwitch from one host to another. 3 | # 4 | #Written by Eric Tekrony 5 | # 6 | #v.1 1/13/2012 7 | 8 | 9 | #Connect to Source Host 10 | #$sourcehost = Read-Host "Please enter the SOURCE host" 11 | #Connect-VIServer -Server $sourcehost -User "root" -Password "H0me*Brew3r" 12 | 13 | #Get and export port groups for source vSwitch 14 | #$vSwitch = Read-Host "Which vSwitch would you like to copy" 15 | 16 | #Get-VirtualSwitch -Name $vSwitch | Get-VirtualPortGroup | Foreach { 17 | # Get-VirtualPortGroup | Export-Csv -Path "D:\Script_Repo\CSVs\exported-vlans.csv" 18 | #} 19 | 20 | #Disconnect-VIServer 21 | 22 | $newhost = Read-Host "Please enter the NEW host" 23 | Connect-VIServer -Server omaedcapp099 -User "ipgna\esb.service" -Password "Password1" 24 | 25 | $vSwitch = Read-Host "Name of new vSwitch" 26 | 27 | $vSwitch_config = Import-Csv "D:\Script_Repo\CSVs\exported-vlans.csv" 28 | Get-Host $newhost 29 | Get-VirtualSwitch -Name $vSwitch 30 | 31 | Foreach ($portgroup in $vSwitch_config) { 32 | #Write-Host "Creating Portgroup $portgroup.Name" 33 | Get-VirtualSwitch -Name $vSwitch | New-VirtualPortGroup -Name $portgroup.Name -VLanId $portgroup.VLanID 34 | } 35 | 36 | Disconnect-VIServer 37 | 38 | #$VISRV = Connect-VIServer (Read-Host "Please enter the name of your VI SERVER") 39 | #$BASEHost = Get-VMHost -Name (Read-Host "Please enter the name of your existing server as seen in the VI Client:") 40 | #$NEWHost = Get-VMHost -Name (Read-Host "Please enter the name of the server to configure as seen in the VI Client:") 41 | 42 | #$BASEHost |Get-VirtualSwitch |Foreach { 43 | # If (($NEWHost |Get-VirtualSwitch -Name $_.Name-ErrorAction SilentlyContinue)-eq $null){ 44 | # Write-Host "Creating Virtual Switch $($_.Name)" 45 | # $NewSwitch = $NEWHost |New-VirtualSwitch -Name $_.Name-NumPorts $_.NumPorts-Mtu $_.Mtu 46 | # $vSwitch = $_ 47 | # } 48 | # $_ |Get-VirtualPortGroup |Foreach { 49 | # If (($NEWHost |Get-VirtualPortGroup -Name $_.Name-ErrorAction SilentlyContinue)-eq $null){ 50 | # Write-Host "Creating Portgroup $($_.Name)" 51 | # $NewPortGroup = $NEWHost |Get-VirtualSwitch -Name $vSwitch |New-VirtualPortGroup -Name $_.Name-VLanId $_.VLanID 52 | # } 53 | # } 54 | #} 55 | 56 | -------------------------------------------------------------------------------- /Copy-From-Datastore.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes 2 | #: December 01, 2015 3 | #: Purpose of script is to list available datastores, allow the user to select one to copy items from and assign it drive letter 'ds:' 4 | #: Allows the option to download files that may have a lock on them, not possible in the web client. 5 | 6 | ######################### 7 | # Set variables here. # 8 | ######################### 9 | 10 | $server = "test-vcsa6" 11 | $user = 'administrator@vsphere.local' 12 | $pass = 'Gn0moAr!' 13 | $drive = "ds" 14 | 15 | ##################### 16 | # End variables # 17 | ##################### 18 | 19 | Write-Host "" 20 | Write-Host "Checking vCenter server connection..." -Foreground "Yellow" 21 | 22 | # Checks the current connection status and connects if needed. 23 | if ($Global:DefaultVIServers.count -eq 0){ 24 | Write-Host "Not connected to vCenter, connecting now..." -ForegroundColor Yellow 25 | Connect-VIServer -Server $server -User $user -Password $pass 26 | } 27 | else{ 28 | Write-Host "Connected to vCenter already, continuing..." -Foreground "Yellow" 29 | Write-Host "" 30 | } 31 | 32 | Write-Host "" 33 | Write-Host "==============================" 34 | Write-Host "vCenter Server = " $Global:DefaultVIServers[0] -ForegroundColor Cyan 35 | Write-Host "==============================" 36 | 37 | # Listing possible datastores to use, displays Name, Free Space, and Capacity. 38 | Write-Host "" 39 | Write-Host "Here are the available datastores..." 40 | Get-Datastore | Sort Name | Select Name, FreeSpaceGB, CapacityGB | FT -AutoSize 41 | 42 | # Set datastore using input from user. 43 | Write-Host "Enter target datastore name: " -Fore Green -NoNewLine 44 | $targetDatastore = Read-Host 45 | $finalDatastore = Get-Datastore $targetDatastore 46 | 47 | # Set new PSDrive to use for copying desired files. Set with variable at top of script. 48 | New-PSDrive -Location $finalDatastore -Name $drive -PSProvider VimDatastore -Root "\" -Scope "Global" 49 | sl ds: 50 | 51 | # Providing format to save desired file. Also serves reminder to remove the drive when done. 52 | Write-Host "Syntax for copying file is:" 53 | Write-Host "" 54 | Write-Host "Copy-DatastoreItem -Item [-Destination DestinationLocation] [-Force] [-Recurse] [-Confirm]" -Fore Magenta 55 | Write-Host "" 56 | Write-Host "!! Run 'Remove-PSDrive ds' command after you are finished !!" -ForegroundColor Red 57 | Write-Host "" 58 | -------------------------------------------------------------------------------- /Datacenter-Get-VM-Storage.ps1: -------------------------------------------------------------------------------- 1 | #################################### 2 | # 3 | #: Title: DataCenter-Get-VM-Storage 4 | #: Author: Andru Estes. 5 | #: Date October 27th, 2015 6 | # 7 | #################################### 8 | 9 | # Seting the datacenter by using the specific DataCenter name. 10 | # Uses user input data. 11 | 12 | $title = "Datacenter choice..." 13 | $message = "Which datacenter would you like to use? (Enter first letter)" 14 | 15 | # Setting the different DataCenter options. Letting the user choose. 16 | $dc1 = New-Object System.Management.Automation.Host.ChoiceDescription "&OMA", "OMA" 17 | $dc2 = New-Object System.Management.Automation.Host.ChoiceDescription "&LDN", "LDN" 18 | $dc3 = New-Object System.Management.Automation.Host.ChoiceDescription "&CHI", "CHI" 19 | $dcOptions = [System.Management.Automation.Host.ChoiceDescription[]]($dc1, $dc2, $dc3) 20 | $chosenDC = $host.ui.PromptForChoice($title, $message, $dcOptions, 0) 21 | 22 | # Using if statements to check which option the user chose, passing it to global variable vDC for later processing. 23 | if($chosenDC -eq "0"){ 24 | $global:vDC = "OMA" 25 | } 26 | elseif($chosenDC -eq "1"){ 27 | $global:vDC = "LDN" 28 | } 29 | elseif($chosenDC -eq "2"){ 30 | $global:vDC = "CHI" 31 | } 32 | 33 | $clusterOptions = Get-Datacenter $global:vDC | Get-Cluster 34 | 35 | "" 36 | 37 | Write-Host "Below are your cluster choices..." 38 | 39 | foreach($cluster in $clusterOptions){ 40 | $cluster 41 | } 42 | 43 | "" 44 | 45 | $clusterChoice = Read-Host "Specify the cluster if desired, otherwise enter q" 46 | 47 | if($clusterChoice -ne "q"){ 48 | Get-Datacenter -Name $global:vDC | 49 | Get-Cluster -Name $clusterChoice | 50 | Get-VM | 51 | Select Name, 52 | @{N="Datastore";E={[string]::Join(',',(Get-Datastore -Id $_.DatastoreIdList | Select -ExpandProperty Name))}}, 53 | #@{N="UsedSpaceGB";E={[math]::Round($_.UsedSpaceGB,1)}}, 54 | @{N="ProvisionedSpaceGB";E={[math]::Round($_.ProvisionedSpaceGB,1)}}, 55 | @{N="Folder";E={$_.Folder.Name}} | 56 | Export-Csv C:\${clusterChoice}-VM-Storage-report.csv -NoTypeInformation -UseCulture 57 | exit 58 | } 59 | 60 | elseif($clusterChoice -eq "q"){ 61 | Get-Datacenter -Name $global:vDC | 62 | Get-VM | 63 | Select Name, 64 | @{N="Datastore";E={[string]::Join(',',(Get-Datastore -Id $_.DatastoreIdList | Select -ExpandProperty Name))}}, 65 | #@{N="UsedSpaceGB";E={[math]::Round($_.UsedSpaceGB,1)}}, 66 | @{N="ProvisionedSpaceGB";E={[math]::Round($_.ProvisionedSpaceGB,1)}}, 67 | @{N="Folder";E={$_.Folder.Name}} | 68 | Export-Csv C:\${global:vDC}-VM-Storage-report.csv -NoTypeInformation -UseCulture 69 | } 70 | 71 | -------------------------------------------------------------------------------- /In Development/Get-vSphere5Licenses.ps1: -------------------------------------------------------------------------------- 1 | $vCenterServerName = "drsedcapp099" # Enter your vCenter server name here. In case of multiple vCenter servers, separate using a comma. 2 | 3 | $ErrorActionPreference = "Stop" 4 | 5 | # Connect to vCenter(s) 6 | Write-Host "Connecting..." 7 | $VC = Connect-VIServer $vCenterServerName 8 | 9 | Write-Host "Counting physical cpu's and vRAM in your environment. Please be patient..." 10 | # Gather information 11 | $pCpu = (Get-VMHost | Get-View | Select -ExpandProperty Hardware | Select -ExpandProperty CpuInfo | Measure-Object -Property NumCpuPackages -Sum).Sum 12 | $vRAM = [Math]::Round((Get-VM | Where {$_.PowerState -eq "PoweredOn"} | Measure-Object -Property MemoryMB -Sum).Sum/1024,0) 13 | Write-Host "======" 14 | "pCpu Count: {0}" -f $pCpu 15 | "vRAM (GB): {0}" -f $vRAM 16 | Write-Host "======" 17 | # Disconnect 18 | Disconnect-VIServer $vCenterServerName -Confirm:$false 19 | 20 | # Calculate required licenses 21 | $licCol = @() 22 | $licObj = "" | Select Edition, Entitlement, Licenses 23 | $licObj.Edition = "Essentials/Essentials Plus/Standard" 24 | $licObj.Entitlement = "1 pCpu + 24 GB vRAM" 25 | If (($vRAM/24) -gt $pCpu) 26 | { 27 | $licObj.Licenses = "{0} with {1} pCpu overhead" -f [Math]::Ceiling($vRAM/24), ([Math]::Ceiling($vRAM/24) - $pCpu) 28 | } 29 | Else 30 | { 31 | $licObj.Licenses = "{0} with {1} GB vRAM overhead" -f $pCpu, ((24 * $pCpu) - $vRAM) 32 | } 33 | $licCol += $licObj 34 | $licObj = "" | Select Edition, Entitlement, Licenses 35 | $licObj.Edition = "Enterprise" 36 | $licObj.Entitlement = "1 pCpu + 32 GB vRAM" 37 | If (($vRAM/32) -gt $pCpu) 38 | { 39 | $licObj.Licenses = "{0} with {1} pCpu overhead" -f [Math]::Ceiling($vRAM/32), ([Math]::Ceiling($vRAM/32) - $pCpu) 40 | } 41 | Else 42 | { 43 | $licObj.Licenses = "{0} with {1} GB vRAM overhead" -f $pCpu, ((32 * $pCpu) - $vRAM) 44 | } 45 | $licCol += $licObj 46 | $licObj = "" | Select Edition, Entitlement, Licenses 47 | $licObj.Edition = "Enterprise Plus" 48 | $licObj.Entitlement = "1 pCpu + 48 GB vRAM" 49 | If (($vRAM/48) -gt $pCpu) 50 | { 51 | $licObj.Licenses = "{0} with {1} pCpu overhead" -f [Math]::Ceiling($vRAM/48), ([Math]::Ceiling($vRAM/48) - $pCpu) 52 | } 53 | Else 54 | { 55 | $licObj.Licenses = "{0} with {1} GB vRAM overhead" -f $pCpu, ((48 * $pCpu) - $vRAM) 56 | } 57 | $licCol += $licObj 58 | # Displaying output 59 | Write-Host "Resulting license options:" 60 | $licCol 61 | Write-Host "======" 62 | Write-Host "NOTE: vRAM only counts memory allocated to vm's that are POWERED ON." -ForegroundColor Red 63 | Write-Host "NOTE: Please double check the results of this script, since hosts may have been omitted due to errors." -ForegroundColor Red 64 | Write-Host "Disclaimer: No rights can be deduced from this calculation." -ForegroundColor Red 65 | Write-Host "======" -------------------------------------------------------------------------------- /GUI-Storage-vMotion.ps1: -------------------------------------------------------------------------------- 1 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 2 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 3 | 4 | $cluster = Read-Host "Enter Cluster" 5 | $datastores = Get-Cluster $cluster | Get-Datastore | Select Name 6 | $vm = Read-Host "Enter desired VM" 7 | 8 | ############################################### 9 | ### Creating Form for Input ### 10 | ############################################### 11 | 12 | $objForm = New-Object System.Windows.Forms.Form 13 | $objForm.Text = "Select a Computer" 14 | $objForm.Size = New-Object System.Drawing.Size(300,200) 15 | $objForm.StartPosition = "CenterScreen" 16 | 17 | $objForm.KeyPreview = $True 18 | $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 19 | {$x=$objListBox.SelectedItem;$objForm.Close()}}) 20 | $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 21 | {$objForm.Close()}}) 22 | 23 | $OKButton = New-Object System.Windows.Forms.Button 24 | $OKButton.Location = New-Object System.Drawing.Size(75,140) 25 | $OKButton.Size = New-Object System.Drawing.Size(75,23) 26 | $OKButton.Text = "OK" 27 | $OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()}) 28 | $objForm.Controls.Add($OKButton) 29 | 30 | $CancelButton = New-Object System.Windows.Forms.Button 31 | $CancelButton.Location = New-Object System.Drawing.Size(150,140) 32 | $CancelButton.Size = New-Object System.Drawing.Size(75,23) 33 | $CancelButton.Text = "Cancel" 34 | $CancelButton.Add_Click({$objForm.Close()}) 35 | $objForm.Controls.Add($CancelButton) 36 | 37 | $objLabel = New-Object System.Windows.Forms.Label 38 | $objLabel.Location = New-Object System.Drawing.Size(10,40) 39 | $objLabel.Size = New-Object System.Drawing.Size(280,20) 40 | $objLabel.Text = "Please select a datastore:" 41 | $objForm.Controls.Add($objLabel) 42 | 43 | $objLabel = New-Object System.Windows.Forms.Label 44 | $objLabel.Location = New-Object System.Drawing.Size(10,20) 45 | $objLabel.Size = New-Object System.Drawing.Size(280,20) 46 | $objLabel.Text = "VM Name: $vm" 47 | $objForm.Controls.Add($objLabel) 48 | 49 | 50 | $objListBox = New-Object System.Windows.Forms.ListBox 51 | $objListBox.Location = New-Object System.Drawing.Size(10,60) 52 | $objListBox.Size = New-Object System.Drawing.Size(260,20) 53 | $objListBox.Height = 80 54 | 55 | ForEach($ds in $datastores){ 56 | [void] $objListBox.Items.Add($ds) 57 | } 58 | 59 | <# 60 | [void] $objListBox.Items.Add("atl-dc-001") 61 | [void] $objListBox.Items.Add("atl-dc-002") 62 | [void] $objListBox.Items.Add("atl-dc-003") 63 | [void] $objListBox.Items.Add("atl-dc-004") 64 | [void] $objListBox.Items.Add("atl-dc-005") 65 | [void] $objListBox.Items.Add("atl-dc-006") 66 | [void] $objListBox.Items.Add("atl-dc-007") 67 | #> 68 | 69 | $objForm.Controls.Add($objListBox) 70 | 71 | $objForm.Topmost = $True 72 | 73 | $objForm.Add_Shown({$objForm.Activate()}) 74 | [void] $objForm.ShowDialog() 75 | 76 | ################################### 77 | ### Ending Form ### 78 | ################################### 79 | 80 | $x -------------------------------------------------------------------------------- /ESXi-Shutdown-Hosts-and-VMs.ps1: -------------------------------------------------------------------------------- 1 | ################################################################################# 2 | # Shutdown VMs and Hosts 3 | # 4 | # This script will loop through a list of ESXi hosts and initiate shutdown 5 | # commands to the vm's residing on them. If VMware Tools is installed, the 6 | # script will attempt to do a graceful shutdown. If VMware tools is not 7 | # installed a hard power off will be issued. One note, if you have any VMs that 8 | # you would like to remain on until the end of the process be sure to put their 9 | # names in the $vmstoleaveon variable and also be sure they reside on the last 10 | # host listed in the $hoststoprocess variable. 11 | # 12 | # i.e If I wanted to have VM1 and VM2 stay on till the end I would have to be 13 | # sure that they reside on esxi-03 and my variables would be setup as follows 14 | # 15 | # $vmstoleaveon = "VM1 VM2" 16 | # $listofhosts = "esxi-01 esxi-02 esxi-03" 17 | # 18 | # Created By: Mike Preston, 2011 19 | # Updates: MWP - March 2012 - how not looks to see if any VMs are still on after 20 | # doing initial shutdown, then runs a hard stop, and enters 21 | # maintenance mode before shutting down. 22 | # 23 | ################################################################################# 24 | 25 | # list of hosts to process 26 | $listofhosts = "esxi-01", "esxi-02", "esxi-03" 27 | 28 | #list of vm's to 'go down with the ship' - vms must reside on last host in above list. 29 | $vmstoleave = "VM1", "VM2" 30 | 31 | #loop through each host 32 | Foreach ($esxhost in $listofhosts) 33 | { 34 | $currentesxhost = get-vmhost $esxhost 35 | Write-Host "Processing $currentesxhost" 36 | 37 | #loop through each vm on host 38 | Foreach ($VM in ($currentesxhost | Get-VM | where { $_.PowerState -eq "PoweredOn" })) 39 | { 40 | Write-Host "====================================================================" 41 | Write-Host "Processing $vm" 42 | 43 | # if this is a vm that is supposed to go down with the ship. 44 | if ($vmstoleave -contains $vm) 45 | { 46 | Write-Host "I am $vm - I will go down with the ship" 47 | } 48 | else 49 | { 50 | Write-Host "Checking VMware Tools...." 51 | $vminfo = get-view -Id $vm.ID 52 | # If we have VMware tools installed 53 | if ($vminfo.config.Tools.ToolsVersion -eq 0) 54 | { 55 | Write-Host "$vm doesn't have vmware tools installed, hard power this one" 56 | # Hard Power Off 57 | Stop-VM $vm -confirm:$false 58 | 59 | } 60 | else 61 | { 62 | write-host "I will attempt to shutdown $vm" 63 | # Power off gracefully 64 | $vmshutdown = $vm | shutdown-VMGuest -Confirm:$false 65 | } 66 | } 67 | Write-Host "====================================================================" 68 | } 69 | Write-Host "Initiating host shutdown in 40 seconds" 70 | sleep 40 71 | #look for other vm's still powered on. 72 | 73 | Foreach ($VM in ($currentesxhost | Get-VM | where { $_.PowerState -eq "PoweredOn" })) 74 | { 75 | Write-Host "====================================================================" 76 | Write-Host "Processing $vm" 77 | Stop-VM $vm -confirm:$false 78 | Write-Host "====================================================================" 79 | } 80 | 81 | #Shut down the host 82 | Sleep 20 83 | 84 | Set-VMhost -VMhost $currentesxHost -State Maintenance 85 | Sleep 15 86 | 87 | $currentesxhost | Foreach {Get-View $_.ID} | Foreach {$_.ShutdownHost_Task($TRUE)} 88 | 89 | } 90 | Write-Host "Shutdown Complete" 91 | -------------------------------------------------------------------------------- /Set-vSwitch-Settings.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes 2 | #: Novemeber 03, 2015 3 | #: Script to check the current vSwitch settings and alter them if necessary. 4 | 5 | # Reading in arguments passed from "Get-vSwitch-Security" script 6 | if ($args[0] -and $args[1]){ 7 | $datacenter = $args[0] 8 | $cluster = $args[1] 9 | } 10 | else{ 11 | 12 | Write-Host " " 13 | Write-Host "No arguments were passed in..." 14 | 15 | #Listing the datacenters to choose from. 16 | Write-Host " " 17 | Write-Host "Here are the Datacenter choices..." 18 | 19 | $gotDatacenters = Get-Datacenter 20 | 21 | Write-Host $gotDatacenters 22 | 23 | Write-Host " " 24 | 25 | #Setting datacenter variable. 26 | $datacenter = Read-Host "Enter datacenter" 27 | 28 | #Listing clusters to choose from. 29 | Write-Host " " 30 | Write-Host "Below are the clusters to choose from..." 31 | Write-Host " " 32 | 33 | Get-Datacenter -Name $datacenter | Get-Cluster | % {$_.Name} 34 | 35 | Write-Host " " 36 | 37 | #Setting cluster 38 | $cluster = Read-Host "Enter cluster name" 39 | } 40 | Write-Host " " 41 | 42 | # Setting vmHosts to store all hosts within the cluster. 43 | Write-Host "Collecting ESXi hosts..." -Foreground "Green" 44 | $vmHosts = Get-Cluster -Name $cluster | Get-VMHost 45 | 46 | #Listing the current vSwitch settings. 47 | Write-Host "Gathering vSwtich settings for ESXi hosts..." -Foreground "Green" 48 | foreach ($vmHost in $vmHosts){ 49 | Get-VirtualSwitch -VMHost $vmHost -Standard | Select VMhost, Name, ` 50 | @{N="MacChanges";E={if ($_.ExtensionData.Spec.Policy.Security.MacChanges) { "Accept" } Else { "Reject"} }}, ` 51 | @{N="PromiscuousMode";E={if ($_.ExtensionData.Spec.Policy.Security.PromiscuousMode) { "Accept" } Else { "Reject"} }}, ` 52 | @{N="ForgedTransmits";E={if ($_.ExtensionData.Spec.Policy.Security.ForgedTransmits) { "Accept" } Else { "Reject"} }} 53 | } 54 | 55 | Function Set-VirtualSwitchSecurity { 56 | Param ( 57 | [Parameter(Mandatory=$True,ValueFromPipeline=$True)]$vSwitch, 58 | [ValidateSet("Accept","Reject")]$MacAddressChanges, 59 | [ValidateSet("Accept","Reject")]$PromiscuousMode, 60 | [ValidateSet("Accept","Reject")]$ForgedTransmits 61 | ) 62 | Process { 63 | $hostExt = $vSwitch.VMHost.ExtensionData 64 | $networkSystem = get-view $hostExt.ConfigManager.NetworkSystem 65 | $networkSystem.NetworkConfig.Vswitch| Where {$_.name -match $vSwitch.Name} | Foreach { 66 | $switchSpec = $_.spec 67 | if ($PromiscuousMode -eq "Accept") { 68 | $switchSpec.Policy.Security.AllowPromiscuous = $True 69 | } 70 | if ($PromiscuousMode -eq "Reject") { 71 | $switchSpec.Policy.Security.AllowPromiscuous = $False 72 | } 73 | if ($MacAddressChanges -eq "Accept") { 74 | $switchSpec.Policy.Security.MacChanges = $True 75 | } 76 | if ($MacAddressChanges -eq "Reject") { 77 | $switchSpec.Policy.Security.MacChanges = $False 78 | } 79 | if ($ForgedTransmits -eq "Accept") { 80 | $switchSpec.Policy.Security.ForgedTransmits = $True 81 | } 82 | if ($ForgedTransmits -eq "Reject") { 83 | $switchSpec.Policy.Security.ForgedTransmits = $False 84 | } 85 | $NetworkSystem.UpdateVirtualSwitch($vSwitch.Name, $switchSpec) 86 | } 87 | Get-VirtualSwitch -Name $vSwitch.Nameclear -VMHost $vSwitch.VMHost | Select VMHost, Name, ` 88 | @{N="MacChanges";E={if ($_.ExtensionData.Spec.Policy.Security.MacChanges) { "Accept" } Else { "Reject"} }}, ` 89 | @{N="PromiscuousMode";E={if ($_.ExtensionData.Spec.Policy.Security.PromiscuousMode) { "Accept" } Else { "Reject"} }}, ` 90 | @{N="ForgedTransmits";E={if ($_.ExtensionData.Spec.Policy.Security.ForgedTransmits) { "Accept" } Else { "Reject"} }} 91 | } 92 | } 93 | 94 | 95 | #$switchName = Read-Host "Enter target switch name" 96 | #$host = Read-Host "Enter the ESXi host you want to edit" 97 | 98 | #$switch = Read-Host "Enter the switch you wish to change" 99 | $switches = Get-VirtualSwitch -Standard 100 | Write-Host "Changing vSwitch settings to desired options..." -Foreground "Green" 101 | 102 | foreach ($vswitch in $switches){ 103 | Get-VirtualSwitch -Standard -Name $vswitch | Set-VirtualSwitchSecurity -MacAddressChanges Accept -PromiscuousMode Reject -ForgedTransmits Reject 104 | #Get-VirtualSwitch -VMHost $host -Name $switchName | Set-VirtualSwitchSecurity -MacAddressChanges Accept -PromiscuousMode Reject -ForgedTransmits Accept 105 | } -------------------------------------------------------------------------------- /Power-On-VMs.ps1: -------------------------------------------------------------------------------- 1 | ################################################################################# 2 | # Power On the Powered Off VMs (poweronvms.ps1) 3 | # 4 | # This script is a partner script to the poweroffvms.ps1 script. Basically this 5 | # script will look at the csv file that was dumped by poweroffvms.ps1 and power 6 | # on all of the VMs in the file. It's meant to be run automatically on startup 7 | # but don't worry, it won't always try and power things on, it only will go if 8 | # the power off dump file exists. 9 | # 10 | # This script does have a 'partner' script that powers the VMs off, you can 11 | # grab that script at http://blog.mwpreston.net/shares/ 12 | # 13 | # Created By: Mike Preston, 2012 - With a whole lot of help from Eric Wright 14 | # (@discoposse) 15 | # 16 | # Variables: $vcenter - The IP/DNS of your vCenter Server 17 | # $username/password - credentials for your vCenter Server 18 | # $filename - name of the file that poweroffvms.ps1 dumps 19 | # $myImportantVMs - list of VMS to be powered on first 20 | # 21 | # 22 | # Usage: ./poweronvms.ps1 23 | # 24 | # 25 | ################################################################################# 26 | 27 | Add-PSSnapin VMware.VimAutomation.Core 28 | 29 | #some variables 30 | $vcenter = "vCenterServer" 31 | $username = "user" 32 | $password = "Password" 33 | $filename = "c:\path\to\poweredonguests.csv" 34 | $myImportantVMs = "SQLSERVER01", "DHCPSERVER02" 35 | 36 | #check if the power on file exists - if it does, then there was a power outage... or someone ran it manually GRRRRR 37 | Write-Host "Checking to see if Power Off dump file exists....." -nonewline 38 | Sleep 2 39 | if (Test-Path $filename) 40 | { 41 | Write-Host "File Found" -Foregroundcolor green 42 | Write-Host "" 43 | $date = ( get-date ).ToString('yyyyMMdd-HHmmss') 44 | #now we must check to see if vCenter service is running, if not, we need to wait.... 45 | Write-Host "Checking for vCenter Service..." -nonewline 46 | Sleep 2 47 | while ((Get-Service vpxd).Status -ne "Running") 48 | { 49 | Write-Host "." -nonewline 50 | Sleep 2 51 | Write-Host "." -nonewline 52 | Sleep 2 53 | Write-Host "." -nonewline 54 | Sleep 2 55 | } 56 | Write-Host "Service has Started!" -ForegroundColor Green 57 | #connect to vcenter 58 | Sleep 5 59 | Write-Host "Connecting to vCenter Server..." -nonewline 60 | Sleep 3 61 | $success = Connect-VIServer $vcenter -username $username -Password $password 62 | if ($success) 63 | { 64 | Write-Host "Connected" -ForegroundColor Green 65 | } 66 | else 67 | { 68 | Write-Host "ISSUES, aborting script" -Foregroundcolor Red 69 | exit 70 | } 71 | Write-Host "" 72 | Write-Host "Starting the most important VMs first (Phase 1)" -ForegroundColor Green 73 | Write-Host "" 74 | foreach ($iVM in $myImportantVMs) 75 | { 76 | Write-Host "Powering on $iVM ..." -nonewline 77 | Start-VM $iVM 78 | Sleep 5 79 | Write-Host "DONE" -Foregroundcolor Green 80 | } 81 | Write-Host "" 82 | Write-Host "Starting the remaining VMs" -ForegroundColor Green 83 | Write-Host "" 84 | #read file and start VMs every 5 seconds... 85 | $vms = Import-CSV $filename 86 | foreach ($vm in $vms) 87 | { 88 | $vmname = $vm.Name 89 | if ($myImportantVMs -notcontains $vmName) 90 | { 91 | Start-VM $vm.Name 92 | Write-Host "Powering on $vmName " 93 | sleep 5 94 | Write-Host "DONE" 95 | } 96 | else 97 | { 98 | Write-Host "Skipping $vmname - already powered on in phase 1" -Foregroundcolor yellow 99 | } 100 | } 101 | Write-Host "Power on completed, I will now rename the dump file...." -nonewline 102 | $DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S" 103 | $fileObj = get-item $fileName 104 | $extOnly = $fileObj.extension 105 | $nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'') 106 | rename-item "$fileName" "$nameOnly-$DateStamp$extOnly" 107 | Write-Host "DONE" -foregroundcolor green 108 | Write-Host "File has been renamed to $nameOnly-$DateStamp$extOnly" 109 | } 110 | else 111 | { 112 | Write-Host "File Not Found - aborting..." -Foregroundcolor green 113 | exit 114 | } -------------------------------------------------------------------------------- /In Development/vSphere 4.1 Hardening -- Guest VMs.ps1: -------------------------------------------------------------------------------- 1 | #Virtual Machine Hardening Script v.1 2 | #All page numbers reference "VMware vSphere 4.1 Security Hardening Guide" 3 | #Updated document can be found here: http://communities.vmware.com/docs/DOC-15413 4 | # 5 | #Written by Eric Tekrony 6 | # 7 | #v.1 6/16/2011 8 | 9 | #Prompt and Connect to vCenter Server 10 | $vcenter = Read-Host "Enter a vCenter server:" 11 | Connect-VIServer -Server $vcenter -Protocol HTTPS -User "ipgna\esb.service" -Password "Password1" 12 | 13 | #Prompt for Datacenter and Cluster 14 | #$datacenter = Read-Host "`nEnter Datacenter: " 15 | #$cluster = Read-Host "`nEnter Cluster: " 16 | 17 | #Get Guest machines in cluster from vCenter server 18 | #Write-Host "`nCollecting all VMs in $cluster..." 19 | #$vmguests = Get-Datacenter $datacenter | Get-Cluster $cluster | Get-VMGuest 20 | #Write-Host "done!" 21 | 22 | #Get Guest machines from CSV file 23 | $vmcsv = import-csv "D:\Script_Repo\CSVs\VMHardening.csv" 24 | 25 | #Create new Virtual Machince Config Spec 26 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 27 | 28 | #Create temp options array 29 | $temp = New-Object VMware.Vim.optionvalue 30 | 31 | 32 | #Write new config options to VMs using array 33 | #foreach ($vmguest in $vmguests){ 34 | # $vm = Get-VM $vmguest.vm 35 | # Write-Host "`nWriting new config to $vm..." 36 | # $vm.Extensiondata.ReconfigVM($vmConfigSpec) 37 | # Write-Host "done!" 38 | #} 39 | 40 | #Write new config options to VMs using csv 41 | foreach ($vmguest in $vmcsv){ 42 | $vm = Get-VM $vmguest.name 43 | Write-Host "`nWriting new config to $vm..." 44 | #Set Disk Shrink tools to disabled p.12 45 | $temp.Key = “isolation.tools.diskShrink.disable” 46 | $temp.Value = "TRUE" 47 | $vmConfigSpec.extraconfig += $temp 48 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 49 | $temp.Key = “isolation.tools.diskWiper.disable” 50 | $temp.Value ="TRUE" 51 | $vmConfigSpec.extraconfig += $temp 52 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 53 | 54 | #Set number of remote display sessions for users to 1 p.13 55 | $temp.Key = "RemoteDisplay.maxConnections" 56 | $temp.Value = "1" 57 | $vmConfigSpec.extraconfig += $temp 58 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 59 | 60 | #Restrict certain hardware devices p.14 61 | $temp.Key = "floppy0.present" 62 | $temp.Value = "false" 63 | $vmConfigSpec.extraconfig += $temp 64 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 65 | #$temp.Key = "serialX.present" 66 | #$temp.Value = "false" 67 | #$vmConfigSpec.extraconfig += $temp 68 | #$temp.Key = "parallelX.present" 69 | #$temp.Value = "false" 70 | #$vmConfigSpec.extraconfig += $temp 71 | #$temp.Key = "usb.present" 72 | #$temp.Value = "false" 73 | #$vmConfigSpec.extraconfig += $temp 74 | 75 | #Restrict VMCI communication between VMs p.16 76 | $temp.Key = "vmci0.unrestricted" 77 | $temp.Value = "FALSE" 78 | $vmConfigSpec.extraconfig += $temp 79 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 80 | 81 | #Configure log file size to match storage blocks p.17 82 | $temp.Key = "log.rotateSize" 83 | $temp.Value = "4000000" 84 | $vmConfigSpec.extraconfig += $temp 85 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 86 | $temp.Key = "log.keepOld" 87 | $temp.Value = "5" 88 | $vmConfigSpec.extraconfig += $temp 89 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 90 | 91 | #Disable certain Workstation/Fusion features p.20 92 | $temp.Key = "isolation.tools.unity.push.update.disable" 93 | $temp.Value = "TRUE" 94 | $vmConfigSpec.extraconfig += $temp 95 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 96 | $temp.Key = "isolation.tools.ghi.launchmenu.change" 97 | $temp.Value = "TRUE" 98 | $vmConfigSpec.extraconfig += $temp 99 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 100 | $temp.Key = "isolation.tools.memSchedFakeSampleS" 101 | $temp.Value = "TRUE" 102 | $vmConfigSpec.extraconfig += $temp 103 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 104 | $temp.Key = "isolation.tools.getCreds.disable" 105 | $temp.Value = "TRUE" 106 | $vmConfigSpec.extraconfig += $temp 107 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 108 | 109 | #Disable Host reporting to guest performance data p.22 110 | $temp.Key = "tools.guestlib.enableHostInfo" 111 | $temp.Value = "false" 112 | $vmConfigSpec.extraconfig += $temp 113 | $vm.Extensiondata.ReconfigVM($vmConfigSpec) 114 | Write-Host "done!" 115 | } 116 | 117 | #Disconnect from vCenter 118 | Disconnect-VIServer -Confirm:$false 119 | Write-Host "All done." -------------------------------------------------------------------------------- /vCheck/snapshot-info.ps1: -------------------------------------------------------------------------------- 1 | # Start of Settings 2 | # Set the warning threshold for snapshots in days old 3 | $SnapshotAge = 0 4 | # Set snapshot name exception (regex) 5 | $excludeName = "ExcludeMe" 6 | # Set snapshot description exception (regex) 7 | $excludeDesc = "ExcludeMe" 8 | # Set snapshot creator exception (regex) 9 | $excludeCreator = "ExcludeMe" 10 | # End of Settings 11 | 12 | # Changelog 13 | ## 1.3 : Cleanup - Fixed Creator - Changed Size to GB 14 | ## 1.4 : Decode URL-encoded snapshot name (i.e. the %xx caharacters) 15 | 16 | Add-Type -AssemblyName System.Web 17 | 18 | function Get-SnapshotSummary { 19 | param( 20 | $InputObject = $null 21 | ) 22 | 23 | PROCESS { 24 | if ($InputObject -and $_) { 25 | throw 'ParameterBinderStrings\AmbiguousParameterSet' 26 | break 27 | } elseif ($InputObject) { 28 | $InputObject 29 | } elseif ($_) { 30 | 31 | $mySnaps = @() 32 | foreach ($snap in $_){ 33 | $SnapshotInfo = Get-SnapshotExtra $snap 34 | $mySnaps += $SnapshotInfo 35 | } 36 | 37 | $mySnaps | Select VM, @{N="SnapName";E={[System.Web.HttpUtility]::UrlDecode($_.Name)}}, @{N="DaysOld";E={((Get-Date) - $_.Created).Days}}, Creator, @{N="SizeGB";E={$_.SizeGB -as [int]}}, Created, Description -ErrorAction SilentlyContinue | Sort DaysOld 38 | 39 | } else { 40 | throw 'ParameterBinderStrings\InputObjectNotBound' 41 | } 42 | } 43 | } 44 | 45 | function Get-SnapshotTree{ 46 | param($tree, $target) 47 | 48 | $found = $null 49 | foreach($elem in $tree){ 50 | if($elem.Snapshot.Value -eq $target.Value){ 51 | $found = $elem 52 | continue 53 | } 54 | } 55 | if($found -eq $null -and $elem.ChildSnapshotList -ne $null){ 56 | $found = Get-SnapshotTree $elem.ChildSnapshotList $target 57 | } 58 | 59 | return $found 60 | } 61 | 62 | function Get-SnapshotExtra ($snap){ 63 | $guestName = $snap.VM # The name of the guest 64 | $tasknumber = 999 # Window size of the Task collector 65 | $taskMgr = Get-View TaskManager 66 | 67 | # Create hash table. Each entry is a create snapshot task 68 | $report = @{} 69 | 70 | $filter = New-Object VMware.Vim.TaskFilterSpec 71 | $filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime 72 | $filter.Time.beginTime = (($snap.Created).AddDays(-5)) 73 | $filter.Time.timeType = "startedTime" 74 | # Added filter to only view for the selected VM entity. Massive speed up. 75 | # Entity name check could be removed in line 91. 76 | $filter.Entity = New-Object VMware.Vim.TaskFilterSpecByEntity 77 | $filter.Entity.Entity = $snap.VM.ExtensionData.MoRef 78 | 79 | $collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter)) 80 | 81 | $dummy = $collectionImpl.RewindCollector 82 | $collection = $collectionImpl.ReadNextTasks($tasknumber) 83 | while($collection -ne $null){ 84 | $collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{ 85 | $row = New-Object PsObject 86 | $row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reason.UserName 87 | $vm = Get-View $_.Entity 88 | if($vm -ne $null){ 89 | $snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result 90 | if($snapshot -ne $null){ 91 | $key = $_.EntityName + "&" + ($snapshot.CreateTime.ToString()) 92 | $report[$key] = $row 93 | } 94 | } 95 | } 96 | $collection = $collectionImpl.ReadNextTasks($tasknumber) 97 | } 98 | $collectionImpl.DestroyCollector() 99 | 100 | # Get the guest's snapshots and add the user 101 | $snapshotsExtra = $snap | % { 102 | $key = $_.vm.Name + "&" + ($_.Created.ToUniversalTime().ToString()) 103 | $str = $report | Out-String 104 | if($report.ContainsKey($key)){ 105 | $_ | Add-Member -MemberType NoteProperty -Name Creator -Value $report[$key].User 106 | } 107 | $_ 108 | } 109 | $snapshotsExtra 110 | } 111 | 112 | $Snapshots = @($VM | Get-Snapshot | Where {$_.Created -lt (($Date).AddDays(-$SnapshotAge))} | Get-SnapshotSummary | Where {$_.SnapName -notmatch $excludeName -and $_.Description -notmatch $excludeDesc -and $_.Creator -notmatch $excludeCreator}) 113 | $Snapshots 114 | 115 | $Title = "Snapshot Information" 116 | $Header = "Snapshots (Over $SnapshotAge Days Old) : $(@($snapshots).count)" 117 | $Comments = "VMware snapshots which are kept for a long period of time may cause issues, filling up datastores and also may impact performance of the virtual machine." 118 | $Display = "Table" 119 | $Author = "Alan Renouf, Raphael Schitz" 120 | $PluginVersion = 1.4 121 | $PluginCategory = "vSphere" 122 | -------------------------------------------------------------------------------- /In Development/vSphere4.1Hardening - origingal download.ps1: -------------------------------------------------------------------------------- 1 | Connect-VIServer -Server omaedcvcs001 -Protocol HTTPS -User "ipgna\esb.service" -Password "Password1" 2 | $vmcsv = import-csv "D:\hardening.csv" 3 | $vmx01 = “isolation.tools.diskShrink.disable” 4 | $value2 = "True" 5 | $vmx01part2 = “isolation.tools.diskWiper.disable” 6 | $value3 = "True" 7 | $vmx02 = "RemoteDisplay.maxConnections" 8 | $value4 = "1" 9 | $vmx11 = "isolation.device.connectable.disable" 10 | $value5 = "true" 11 | $vmx11part2 = "isolation.device.edit.disable" 12 | $value6 = "true" 13 | $vmx12 = "vmci0.unrestricted" 14 | $value7 = "false" 15 | $vmx20 = "log.rotateSize" 16 | $value8 = "1000000" 17 | $vmx20part2 = "log.keepOld" 18 | $value9 = "10" 19 | $vmx21 = "tools.setInfo.sizeLimit" 20 | $value10 = "1048576" 21 | $vmx23 = "isolation.tools.hgfsSeverSet.disable" 22 | $value11 = "TRUE" 23 | $vmx30 = "guest.command.enabled" 24 | $value12 = "FALSE" 25 | $vmx31 = "tools.guestlib.enableHostInfo" 26 | $value13 = "FALSE" 27 | 28 | 29 | 30 | foreach ($vmguest in $vmcsv){ 31 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 32 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 33 | $vmConfigSpec.extraconfig[0].Key=$vmx01 34 | $vmConfigSpec.extraconfig[0].Value=$value2 35 | 36 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 37 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 38 | $vmConfigSpec.extraconfig[0].Key=$vmx01part2 39 | $vmConfigSpec.extraconfig[0].Value=$value3 40 | 41 | $vm = Get-VM $vmguest.vm | Get-View 42 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 43 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 44 | $vmConfigSpec.extraconfig[0].Key=$vmx02 45 | $vmConfigSpec.extraconfig[0].Value=$value4 46 | $vm.ReconfigVM($vmConfigSpec) 47 | 48 | $vm = Get-VM $vmguest.vm | Get-View 49 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 50 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 51 | $vmConfigSpec.extraconfig[0].Key=$vmx11 52 | $vmConfigSpec.extraconfig[0].Value=$value5 53 | $vm.ReconfigVM($vmConfigSpec) 54 | 55 | $vm = Get-VM $vmguest.vm | Get-View 56 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 57 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 58 | $vmConfigSpec.extraconfig[0].Key=$vmx11part2 59 | $vmConfigSpec.extraconfig[0].Value=$value6 60 | $vm.ReconfigVM($vmConfigSpec) 61 | 62 | $vm = Get-VM $vmguest.vm | Get-View 63 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 64 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 65 | $vmConfigSpec.extraconfig[0].Key=$vmx12 66 | $vmConfigSpec.extraconfig[0].Value=$value7 67 | $vm.ReconfigVM($vmConfigSpec) 68 | 69 | $vm = Get-VM $vmguest.vm | Get-View 70 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 71 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 72 | $vmConfigSpec.extraconfig[0].Key=$vmx20 73 | $vmConfigSpec.extraconfig[0].Value=$value8 74 | $vm.ReconfigVM($vmConfigSpec) 75 | 76 | $vm = Get-VM $vmguest.vm | Get-View 77 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 78 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 79 | $vmConfigSpec.extraconfig[0].Key=$vmx20part2 80 | $vmConfigSpec.extraconfig[0].Value=$value9 81 | $vm.ReconfigVM($vmConfigSpec) 82 | 83 | $vm = Get-VM $vmguest.vm | Get-View 84 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 85 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 86 | $vmConfigSpec.extraconfig[0].Key=$vmx21 87 | $vmConfigSpec.extraconfig[0].Value=$value10 88 | $vm.ReconfigVM($vmConfigSpec) 89 | 90 | $vm = Get-VM $vmguest.vm | Get-View 91 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 92 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 93 | $vmConfigSpec.extraconfig[0].Key=$vmx23 94 | $vmConfigSpec.extraconfig[0].Value=$value11 95 | $vm.ReconfigVM($vmConfigSpec) 96 | 97 | $vm = Get-VM $vmguest.vm | Get-View 98 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 99 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 100 | $vmConfigSpec.extraconfig[0].Key=$vmx30 101 | $vmConfigSpec.extraconfig[0].Value=$value12 102 | $vm.ReconfigVM($vmConfigSpec) 103 | 104 | $vm = Get-VM $vmguest.vm | Get-View 105 | $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 106 | $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue 107 | $vmConfigSpec.extraconfig[0].Key=$vmx31 108 | $vmConfigSpec.extraconfig[0].Value=$value13 109 | $vm.ReconfigVM($vmConfigSpec) 110 | } -------------------------------------------------------------------------------- /Remove-Orphaned-Files.ps1: -------------------------------------------------------------------------------- 1 | function Remove-OrphanedData { 2 | <# 3 | .SYNOPSIS Remove orphaned folders and VMDK files 4 | .DESCRIPTION The function searches orphaned folders and VMDK files 5 | on one or more datastores and reports its findings. 6 | Optionally the function removes the orphaned folders and VMDK files 7 | .NOTES Author: Luc Dekens 8 | .PARAMETER Datastore 9 | One or more datastores. 10 | The default is to investigate all shared VMFS datastores 11 | .PARAMETER Delete 12 | A switch that indicates if you want to remove the folders 13 | and VMDK files 14 | .EXAMPLE 15 | PS> Remove-OrphanedData -Datastore ds1 16 | .EXAMPLE 17 | PS> Get-Datastore ds* | Remove-OrphanedData 18 | .EXAMPLE 19 | PS> Remove-OrphanedData -Datastore $ds -Delete 20 | #> 21 | 22 | [CmdletBinding(SupportsShouldProcess=$true)] 23 | 24 | param( 25 | [parameter(Mandatory=$true,ValueFromPipeline=$true)] 26 | [PSObject[]]$Datastore, 27 | [switch]$Delete 28 | ) 29 | 30 | begin{ 31 | $fldList = @{} 32 | $hdList = @{} 33 | 34 | $fileMgr = Get-View FileManager 35 | } 36 | 37 | process{ 38 | foreach($ds in $Datastore){ 39 | if($ds.GetType().Name -eq "String"){ 40 | $ds = Get-Datastore -Name $ds 41 | } 42 | if($ds.Type -eq "VMFS" -and $ds.ExtensionData.Summary.MultipleHostAccess){ 43 | Get-VM -Datastore $ds | %{ 44 | $_.Extensiondata.LayoutEx.File | where{"diskDescriptor","diskExtent" -contains $_.Type} | %{ 45 | $fldList[$_.Name.Split('/')[0]] = $_.Name 46 | $hdList[$_.Name] = $_.Name 47 | } 48 | } 49 | Get-Template | where {$_.DatastoreIdList -contains $ds.Id} | %{ 50 | $_.Extensiondata.LayoutEx.File | where{"diskDescriptor","diskExtent" -contains $_.Type} | %{ 51 | $fldList[$_.Name.Split('/')[0]] = $_.Name 52 | $hdList[$_.Name] = $_.Name 53 | } 54 | } 55 | 56 | $dc = $ds.Datacenter.Extensiondata 57 | 58 | $flags = New-Object VMware.Vim.FileQueryFlags 59 | $flags.FileSize = $true 60 | $flags.FileType = $true 61 | 62 | $disk = New-Object VMware.Vim.VmDiskFileQuery 63 | $disk.details = New-Object VMware.Vim.VmDiskFileQueryFlags 64 | $disk.details.capacityKb = $true 65 | $disk.details.diskExtents = $true 66 | $disk.details.diskType = $true 67 | $disk.details.thin = $true 68 | 69 | $searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec 70 | $searchSpec.details = $flags 71 | $searchSpec.Query += $disk 72 | $searchSpec.sortFoldersFirst = $true 73 | 74 | $dsBrowser = Get-View $ds.ExtensionData.browser 75 | $rootPath = "[" + $ds.Name + "]" 76 | $searchResult = $dsBrowser.SearchDatastoreSubFolders($rootPath, $searchSpec) 77 | foreach($folder in $searchResult){ 78 | if($fldList.ContainsKey($folder.FolderPath.TrimEnd('/'))){ 79 | foreach ($file in $folder.File){ 80 | if(!$hdList.ContainsKey($folder.FolderPath + $file.Path)){ 81 | New-Object PSObject -Property @{ 82 | Folder = $folder.FolderPath 83 | Name = $file.Path 84 | Size = $file.FileSize 85 | CapacityKB = $file.CapacityKb 86 | Thin = $file.Thin 87 | Extents = [string]::Join(',',($file.DiskExtents)) 88 | } 89 | if($Delete){ 90 | If ($PSCmdlet.ShouldProcess(($folder.FolderPath + " " + $file.Path),"Remove VMDK")){ 91 | $dsBrowser.DeleteFile($folder.FolderPath + $file.Path) 92 | } 93 | } 94 | } 95 | } 96 | } 97 | elseif($folder.File | where {"cos.vmdk","esxconsole.vmdk" -notcontains $_.Path}){ 98 | $folder.File | %{ 99 | New-Object PSObject -Property @{ 100 | Folder = $folder.FolderPath 101 | Name = $_.Path 102 | Size = $_.FileSize 103 | CapacityKB = $_.CapacityKB 104 | Thin = $_.Thin 105 | Extents = [String]::Join(',',($_.DiskExtents)) 106 | } 107 | } 108 | if($Delete){ 109 | if($folder.FolderPath -eq $rootPath){ 110 | $folder.File | %{ 111 | If ($PSCmdlet.ShouldProcess(($folder.FolderPath + " " + $_.Path),"Remove VMDK")){ 112 | $dsBrowser.DeleteFile($folder.FolderPath + $_.Path) 113 | } 114 | } 115 | } 116 | else{ 117 | If ($PSCmdlet.ShouldProcess($folder.FolderPath,"Remove Folder")){ 118 | $fileMgr.DeleteDatastoreFile($folder.FolderPath,$dc.MoRef) 119 | } 120 | } 121 | } 122 | } 123 | } 124 | } 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /Get-LLDPCDPInfo.ps1: -------------------------------------------------------------------------------- 1 | ######################################################################################################### 2 | ## LLDP_CDP_Information.ps1 3 | ## Version 1.0 4 | ## Auxilium Technology AS, November 2014 5 | ## http://www.auxilium.no 6 | ## 7 | ## Description: 8 | ## Sometimes it's useful to know which ports your host(s) are connected to. It's also good to know what 9 | ## kind of switch you have to deal with and if possible, get the firmware version. 10 | ## 11 | ## Script created 20.11.2014 12 | ## Bjørn-Ove Kiil (bok@auxilium.no) 13 | ## 14 | ## Requirement: 15 | ## The switches where your host(s) are connected have to support Link Layer Discovery Protocol (LLDP) or 16 | ## Cisco Discovery Protocol (CDP) and this feature must be enabled in order to get any information out 17 | ## of it. 18 | ## PS! LLDP is only available on host(s) which are a member of a Distributed Virtual Switch!! 19 | ## 20 | ## Usage: 21 | ## .\LLDP_CDP_Information.ps1 22 | ## 23 | ## Ex.: .\LLDP_CDP_Information.ps1 LabCluster 24 | ## 25 | ######################################################################################################### 26 | 27 | # Connect-VIserver your-vcenter-server -user your-user -password your-password 28 | 29 | param($Cluster) ## Input from command line 30 | 31 | if(!($Cluster)) 32 | { 33 | Write-Host -Fore YELLOW "Missing parameter!" 34 | Write-Host -Fore YELLOW "Usage:" 35 | Write-Host -Fore YELLOW ".\LLDP_CDP_Information.ps1 " 36 | Write-Host -Fore YELLOW "" 37 | Write-Host -Fore YELLOW "Example: .\LLDP_CDP_Information.ps1 LabCluster" 38 | exit 39 | } 40 | if(!(Get-Cluster $Cluster -EA SilentlyContinue)) 41 | { 42 | Write-Host -Fore RED "No cluster found with the name: $Cluster " 43 | Pause 44 | Write-Host -Fore YELLOW "These clusters where found in the vCenter you have connected to:" 45 | Get-Cluster | sort Name | Select Name 46 | exit 47 | } 48 | 49 | $vmh = Get-Cluster $Cluster | Get-VMHost | sort name 50 | $LLDPResultArray = @() 51 | $CDPResultArray = @() 52 | 53 | If ($vmh.ConnectionState -eq "Connected" -or $vmh.State -eq "Maintenance") 54 | { 55 | Get-View $vmh.ID | ` 56 | % { $esxname = $_.Name; Get-View $_.ConfigManager.NetworkSystem} | ` 57 | % { foreach ($physnic in $_.NetworkInfo.Pnic) { 58 | $pnicInfo = $_.QueryNetworkHint($physnic.Device) 59 | 60 | foreach( $hint in $pnicInfo ) 61 | { 62 | ## If the switch support LLDP, and you're using Distributed Virtual Swicth with LLDP 63 | if ($hint.LLDPInfo) 64 | { 65 | #$hint.LLDPInfo.Parameter 66 | $LLDPResult = "" | select-object VMHost, PhysicalNic, PhysSW_Port, PhysSW_Name, PhysSW_Description, PhysSW_MGMTIP, PhysSW_MTU 67 | 68 | $LLDPResult.VMHost = $esxname 69 | $LLDPResult.PhysicalNic = $physnic.Device 70 | $LLDPResult.PhysSW_Port = ($hint.LLDPInfo.Parameter | ? { $_.Key -eq "Port Description" }).Value 71 | $LLDPResult.PhysSW_Name = ($hint.LLDPInfo.Parameter | ? { $_.Key -eq "System Name" }).Value 72 | $LLDPResult.PhysSW_Description = ($hint.LLDPInfo.Parameter | ? { $_.Key -eq "System Description" }).Value 73 | $LLDPResult.PhysSW_MGMTIP = ($hint.LLDPInfo.Parameter | ? { $_.Key -eq "Management Address" }).Value 74 | $LLDPResult.PhysSW_MTU = ($hint.LLDPInfo.Parameter | ? { $_.Key -eq "MTU" }).Value 75 | 76 | $LLDPResultArray += $LLDPResult 77 | } 78 | 79 | ## If it's a Cisco switch behind the server ;) 80 | if ($hint.ConnectedSwitchPort) 81 | { 82 | #$hint.ConnectedSwitchPort 83 | $CDPResult = "" | select-object VMHost, PhysicalNic, PhysSW_Port, PhysSW_Name, PhysSW_HWPlatform, PhysSW_Software, PhysSW_MGMTIP, PhysSW_MTU 84 | 85 | $CDPResult.VMHost = $esxname 86 | $CDPResult.PhysicalNic = $physnic.Device 87 | $CDPResult.PhysSW_Port = $hint.ConnectedSwitchPort.PortID 88 | $CDPResult.PhysSW_Name = $hint.ConnectedSwitchPort.DevID 89 | $CDPResult.PhysSW_HWPlatform = $hint.ConnectedSwitchPort.HardwarePlatform 90 | $CDPResult.PhysSW_Software = $hint.ConnectedSwitchPort.SoftwareVersion 91 | $CDPResult.PhysSW_MGMTIP = $hint.ConnectedSwitchPort.MgmtAddr 92 | $CDPResult.PhysSW_MTU = $hint.ConnetedSwitchPort.Mtu 93 | 94 | $CDPResultArray += $CDPResult 95 | } 96 | if(!($hint.LLDPInfo) -and (!($hint.ConnectedSwitchPort))) 97 | { 98 | Write-Host -Fore YELLOW "No CDP or LLDP information available! " 99 | Write-Host -Fore YELLOW "Check if your switches support these protocols and if" 100 | Write-Host -Fore YELLOW "the CDP/LLDP features are enabled." 101 | } 102 | } 103 | } 104 | } 105 | } 106 | 107 | else 108 | { 109 | Write-Host "No host(s) found in Connected or Maintenance state!" 110 | exit 111 | } 112 | 113 | ## Output to screen and/or file 114 | if ($CDPResultArray) 115 | { 116 | $CDPResultArray | ft -autosize 117 | $CDPResultArray | Export-Csv .\CDP_Info_$Cluster.txt -useculture -notypeinformation 118 | } 119 | if ($LLDPResultArray) 120 | { 121 | $LLDPResultArray | ft -autosize 122 | $LLDPResultArray | Export-Csv .\LLDP_Info_$Cluster.txt -useculture -notypeinformation 123 | } 124 | 125 | #disconnect-viserver * -Confirm:$false 126 | -------------------------------------------------------------------------------- /Get-vSwitch-Security.ps1: -------------------------------------------------------------------------------- 1 | #: Andru Estes 2 | #: November 03, 2015 3 | #: Script purpose is to gather all ESXi hosts within the cluster 4 | 5 | 6 | # Creating the menu for the user to choose from. 7 | do { 8 | do { 9 | write-host "" 10 | write-host "Choose the datacenter..." -Foreground Yellow 11 | write-host "A - OMA" 12 | write-host "B - CHI" 13 | write-host "C - LDN" 14 | write-host "D - TEST" 15 | write-host "E - TDC" 16 | write-host "" 17 | write-host "X - Exit" 18 | write-host "" 19 | write-host -nonewline "Type your choice and press Enter: " 20 | 21 | $choice = read-host 22 | 23 | write-host "" 24 | 25 | $ok = $choice -match '^[abcdex]+$' 26 | 27 | if ( -not $ok) { write-host "Invalid selection" } 28 | } until ( $ok ) 29 | 30 | <# switch -Regex ( $choice ) { 31 | "A" 32 | { 33 | write-host "You chose 'OMA'" 34 | } 35 | 36 | "B" 37 | { 38 | write-host "You chose 'CHI'" 39 | } 40 | 41 | "C" 42 | { 43 | write-host "You chose 'LDN'" 44 | } 45 | 46 | "D" 47 | { 48 | write-host "You chose 'TEST'" 49 | } 50 | "E" 51 | { 52 | write-host "You chose 'TDC'" 53 | } 54 | } 55 | #> 56 | } until ( $choice ) 57 | 58 | 59 | #Write-Host "Enter the cluster: " -NoNewLine -Foreground Yellow 60 | if ($choice -eq "A"){ 61 | $datacenter = "OMA" 62 | } 63 | elseif ($choice -eq "B"){ 64 | $datacenter = "CHI" 65 | } 66 | elseif ($choice -eq "C"){ 67 | $datacenter = "LDN" 68 | } 69 | elseif ($choice -eq "D"){ 70 | $datacenter = "TEST" 71 | } 72 | elseif ($choice -eq "E"){ 73 | $datacenter = "TDC" 74 | } 75 | 76 | $clusterChoices = Get-Datacenter -Name $datacenter | Get-Cluster 77 | 78 | foreach ($option in $clusterChoices){ 79 | Write-Host $option -Foreground Green 80 | } 81 | 82 | Write-Host "" 83 | $cluster = Read-Host "Enter a cluster from above" 84 | Write-Host "" 85 | 86 | Write-Host "Gathering ESXi hosts..." -Foreground "Green" 87 | $vmHosts = Get-Datacenter -Name $datacenter | Get-Cluster -Name $cluster | Get-VMHost 88 | 89 | 90 | foreach ($vmHost in $vmHosts){ 91 | Write-Host " " 92 | Write-Host "Host:" $vmHost -Foreground "Green" 93 | Get-VirtualSwitch -VMHost $vmHost -Standard | Select VMhost, Name, ` 94 | #Get-VirtualSwitch -VMHost $vmHost -Standard | Select Name, ` 95 | #Get-VirtualSwitch -Standard | Select VMHost, Name, ` 96 | @{N="MacChanges";E={if ($_.ExtensionData.Spec.Policy.Security.MacChanges) { "Accept" } Else { "Reject"} }}, ` 97 | @{N="PromiscuousMode";E={if ($_.ExtensionData.Spec.Policy.Security.PromiscuousMode) { "Accept" } Else { "Reject"} }}, ` 98 | @{N="ForgedTransmits";E={if ($_.ExtensionData.Spec.Policy.Security.ForgedTransmits) { "Accept" } Else { "Reject"} }} 99 | } 100 | 101 | Function Set-VirtualSwitchSecurity { 102 | Param ( 103 | [Parameter(Mandatory=$True,ValueFromPipeline=$True)]$vSwitch, 104 | [ValidateSet("Accept","Reject")]$MacAddressChanges, 105 | [ValidateSet("Accept","Reject")]$PromiscuousMode, 106 | [ValidateSet("Accept","Reject")]$ForgedTransmits 107 | ) 108 | Process { 109 | $hostExt = $vSwitch.VMHost.ExtensionData 110 | $networkSystem = get-view $hostExt.ConfigManager.NetworkSystem 111 | $networkSystem.NetworkConfig.Vswitch| Where {$_.name -match $vSwitch.Name} | Foreach { 112 | $switchSpec = $_.spec 113 | if ($PromiscuousMode -eq "Accept") { 114 | $switchSpec.Policy.Security.AllowPromiscuous = $True 115 | } 116 | if ($PromiscuousMode -eq "Reject") { 117 | $switchSpec.Policy.Security.AllowPromiscuous = $False 118 | } 119 | if ($MacAddressChanges -eq "Accept") { 120 | $switchSpec.Policy.Security.MacChanges = $True 121 | } 122 | if ($MacAddressChanges -eq "Reject") { 123 | $switchSpec.Policy.Security.MacChanges = $False 124 | } 125 | if ($ForgedTransmits -eq "Accept") { 126 | $switchSpec.Policy.Security.ForgedTransmits = $True 127 | } 128 | if ($ForgedTransmits -eq "Reject") { 129 | $switchSpec.Policy.Security.ForgedTransmits = $False 130 | } 131 | $NetworkSystem.UpdateVirtualSwitch($vSwitch.Name, $switchSpec) 132 | } 133 | Get-VirtualSwitch -Name $vSwitch.Name -VMHost $vSwitch.VMHost | Select VMHost, Name, ` 134 | @{N="MacChanges";E={if ($_.ExtensionData.Spec.Policy.Security.MacChanges) { "Accept" } Else { "Reject"} }}, ` 135 | @{N="PromiscuousMode";E={if ($_.ExtensionData.Spec.Policy.Security.PromiscuousMode) { "Accept" } Else { "Reject"} }}, ` 136 | @{N="ForgedTransmits";E={if ($_.ExtensionData.Spec.Policy.Security.ForgedTransmits) { "Accept" } Else { "Reject"} }} 137 | } 138 | } 139 | 140 | Write-Host "Would you like to change any of the settings? (Yes or No) " -NoNewLine -Foreground Yellow 141 | $proceed = Read-Host 142 | 143 | if ($proceed -eq "Yes" -or $proceed -eq "Y"){ 144 | Z:\Documents\VMware\Scripts\Set-vSwitch-Settings.ps1 $datacenter $cluster 145 | } 146 | else{ 147 | Write-Host " " 148 | Write-Host "All done!" 149 | exit 0 150 | } 151 | 152 | #Get-VirtualSwitch -Name vSwitch2 | Set-VirtualSwitchSecurity -MacAddressChanges Accept -PromiscuousMode Reject -ForgedTransmits Accept 153 | #Get-VirtualSwitch -VMHost "drsedcvmx112.na.corp.ipgnetwork.com" -Name "vSwitch2" | Set-VirtualSwitchSecurity -MacAddressChanges Accept -PromiscuousMode Reject -ForgedTransmits Reject 154 | -------------------------------------------------------------------------------- /DatastoreFunction.ps1: -------------------------------------------------------------------------------- 1 | Function Get-DatastoreMountInfo { 2 | [CmdletBinding()] 3 | Param ( 4 | [Parameter(ValueFromPipeline=$true)] 5 | $Datastore 6 | ) 7 | Process { 8 | $AllInfo = @() 9 | if (-not $Datastore) { 10 | $Datastore = Get-Datastore 11 | } 12 | Foreach ($ds in $Datastore) { 13 | if ($ds.ExtensionData.info.Vmfs) { 14 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].diskname 15 | if ($ds.ExtensionData.Host) { 16 | $attachedHosts = $ds.ExtensionData.Host 17 | Foreach ($VMHost in $attachedHosts) { 18 | $hostview = Get-View $VMHost.Key 19 | $hostviewDSState = $VMHost.MountInfo.Mounted 20 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 21 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 22 | Foreach ($device in $devices) { 23 | $Info = "" | Select Datastore, VMHost, Lun, Mounted, State 24 | if ($device.canonicalName -eq $hostviewDSDiskName) { 25 | $hostviewDSAttachState = "" 26 | if ($device.operationalState[0] -eq "ok") { 27 | $hostviewDSAttachState = "Attached" 28 | } elseif ($device.operationalState[0] -eq "off") { 29 | $hostviewDSAttachState = "Detached" 30 | } else { 31 | $hostviewDSAttachState = $device.operationalstate[0] 32 | } 33 | $Info.Datastore = $ds.Name 34 | $Info.Lun = $hostviewDSDiskName 35 | $Info.VMHost = $hostview.Name 36 | $Info.Mounted = $HostViewDSState 37 | $Info.State = $hostviewDSAttachState 38 | $AllInfo += $Info 39 | } 40 | } 41 | 42 | } 43 | } 44 | } 45 | } 46 | $AllInfo 47 | } 48 | } 49 | 50 | Function Detach-Datastore { 51 | [CmdletBinding()] 52 | Param ( 53 | [Parameter(ValueFromPipeline=$true)] 54 | $Datastore 55 | ) 56 | Process { 57 | if (-not $Datastore) { 58 | Write-Host "No Datastore defined as input" 59 | Exit 60 | } 61 | Foreach ($ds in $Datastore) { 62 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 63 | if ($ds.ExtensionData.Host) { 64 | $attachedHosts = $ds.ExtensionData.Host 65 | Foreach ($VMHost in $attachedHosts) { 66 | $hostview = Get-View $VMHost.Key 67 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 68 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 69 | Foreach ($device in $devices) { 70 | if ($device.canonicalName -eq $hostviewDSDiskName) { 71 | $LunUUID = $Device.Uuid 72 | Write-Host "Detaching LUN $($Device.CanonicalName) from host $($hostview.Name)..." 73 | $StorageSys.DetachScsiLun($LunUUID); 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | } 81 | 82 | Function Unmount-Datastore { 83 | [CmdletBinding()] 84 | Param ( 85 | [Parameter(ValueFromPipeline=$true)] 86 | $Datastore 87 | ) 88 | Process { 89 | if (-not $Datastore) { 90 | Write-Host "No Datastore defined as input" 91 | Exit 92 | } 93 | Foreach ($ds in $Datastore) { 94 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 95 | if ($ds.ExtensionData.Host) { 96 | $attachedHosts = $ds.ExtensionData.Host 97 | Foreach ($VMHost in $attachedHosts) { 98 | $hostview = Get-View $VMHost.Key 99 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 100 | Write-Host "Unmounting VMFS Datastore $($DS.Name) from host $($hostview.Name)..." 101 | $StorageSys.UnmountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); 102 | } 103 | } 104 | } 105 | } 106 | } 107 | 108 | Function Mount-Datastore { 109 | [CmdletBinding()] 110 | Param ( 111 | [Parameter(ValueFromPipeline=$true)] 112 | $Datastore 113 | ) 114 | Process { 115 | if (-not $Datastore) { 116 | Write-Host "No Datastore defined as input" 117 | Exit 118 | } 119 | Foreach ($ds in $Datastore) { 120 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 121 | if ($ds.ExtensionData.Host) { 122 | $attachedHosts = $ds.ExtensionData.Host 123 | Foreach ($VMHost in $attachedHosts) { 124 | $hostview = Get-View $VMHost.Key 125 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 126 | Write-Host "Mounting VMFS Datastore $($DS.Name) on host $($hostview.Name)..." 127 | $StorageSys.MountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); 128 | } 129 | } 130 | } 131 | } 132 | } 133 | 134 | Function Attach-Datastore { 135 | [CmdletBinding()] 136 | Param ( 137 | [Parameter(ValueFromPipeline=$true)] 138 | $Datastore 139 | ) 140 | Process { 141 | if (-not $Datastore) { 142 | Write-Host "No Datastore defined as input" 143 | Exit 144 | } 145 | Foreach ($ds in $Datastore) { 146 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 147 | if ($ds.ExtensionData.Host) { 148 | $attachedHosts = $ds.ExtensionData.Host 149 | Foreach ($VMHost in $attachedHosts) { 150 | $hostview = Get-View $VMHost.Key 151 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 152 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 153 | Foreach ($device in $devices) { 154 | if ($device.canonicalName -eq $hostviewDSDiskName) { 155 | $LunUUID = $Device.Uuid 156 | Write-Host "Attaching LUN $($Device.CanonicalName) to host $($hostview.Name)..." 157 | $StorageSys.AttachScsiLun($LunUUID); 158 | } 159 | } 160 | } 161 | } 162 | } 163 | } 164 | } 165 | # 166 | #Get-Datastore | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 167 | # 168 | #Get-Datastore IX2ISCSI01 | Unmount-Datastore 169 | # 170 | #Get-Datastore IX2ISCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 171 | # 172 | #Get-Datastore IX2iSCSI01 | Mount-Datastore 173 | # 174 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 175 | # 176 | #Get-Datastore IX2iSCSI01 | Detach-Datastore 177 | # 178 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 179 | # 180 | #Get-Datastore IX2iSCSI01 | Attach-datastore 181 | # 182 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 183 | # -------------------------------------------------------------------------------- /DatastoreFunction.txt: -------------------------------------------------------------------------------- 1 | Function Get-DatastoreMountInfo { 2 | [CmdletBinding()] 3 | Param ( 4 | [Parameter(ValueFromPipeline=$true)] 5 | $Datastore 6 | ) 7 | Process { 8 | $AllInfo = @() 9 | if (-not $Datastore) { 10 | $Datastore = Get-Datastore 11 | } 12 | Foreach ($ds in $Datastore) { 13 | if ($ds.ExtensionData.info.Vmfs) { 14 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].diskname 15 | if ($ds.ExtensionData.Host) { 16 | $attachedHosts = $ds.ExtensionData.Host 17 | Foreach ($VMHost in $attachedHosts) { 18 | $hostview = Get-View $VMHost.Key 19 | $hostviewDSState = $VMHost.MountInfo.Mounted 20 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 21 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 22 | Foreach ($device in $devices) { 23 | $Info = "" | Select Datastore, VMHost, Lun, Mounted, State 24 | if ($device.canonicalName -eq $hostviewDSDiskName) { 25 | $hostviewDSAttachState = "" 26 | if ($device.operationalState[0] -eq "ok") { 27 | $hostviewDSAttachState = "Attached" 28 | } elseif ($device.operationalState[0] -eq "off") { 29 | $hostviewDSAttachState = "Detached" 30 | } else { 31 | $hostviewDSAttachState = $device.operationalstate[0] 32 | } 33 | $Info.Datastore = $ds.Name 34 | $Info.Lun = $hostviewDSDiskName 35 | $Info.VMHost = $hostview.Name 36 | $Info.Mounted = $HostViewDSState 37 | $Info.State = $hostviewDSAttachState 38 | $AllInfo += $Info 39 | } 40 | } 41 | 42 | } 43 | } 44 | } 45 | } 46 | $AllInfo 47 | } 48 | } 49 | 50 | Function Detach-Datastore { 51 | [CmdletBinding()] 52 | Param ( 53 | [Parameter(ValueFromPipeline=$true)] 54 | $Datastore 55 | ) 56 | Process { 57 | if (-not $Datastore) { 58 | Write-Host "No Datastore defined as input" 59 | Exit 60 | } 61 | Foreach ($ds in $Datastore) { 62 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 63 | if ($ds.ExtensionData.Host) { 64 | $attachedHosts = $ds.ExtensionData.Host 65 | Foreach ($VMHost in $attachedHosts) { 66 | $hostview = Get-View $VMHost.Key 67 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 68 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 69 | Foreach ($device in $devices) { 70 | if ($device.canonicalName -eq $hostviewDSDiskName) { 71 | $LunUUID = $Device.Uuid 72 | Write-Host "Detaching LUN $($Device.CanonicalName) from host $($hostview.Name)..." 73 | $StorageSys.DetachScsiLun($LunUUID); 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | } 81 | 82 | Function Unmount-Datastore { 83 | [CmdletBinding()] 84 | Param ( 85 | [Parameter(ValueFromPipeline=$true)] 86 | $Datastore 87 | ) 88 | Process { 89 | if (-not $Datastore) { 90 | Write-Host "No Datastore defined as input" 91 | Exit 92 | } 93 | Foreach ($ds in $Datastore) { 94 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 95 | if ($ds.ExtensionData.Host) { 96 | $attachedHosts = $ds.ExtensionData.Host 97 | Foreach ($VMHost in $attachedHosts) { 98 | $hostview = Get-View $VMHost.Key 99 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 100 | Write-Host "Unmounting VMFS Datastore $($DS.Name) from host $($hostview.Name)..." 101 | $StorageSys.UnmountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); 102 | } 103 | } 104 | } 105 | } 106 | } 107 | 108 | Function Mount-Datastore { 109 | [CmdletBinding()] 110 | Param ( 111 | [Parameter(ValueFromPipeline=$true)] 112 | $Datastore 113 | ) 114 | Process { 115 | if (-not $Datastore) { 116 | Write-Host "No Datastore defined as input" 117 | Exit 118 | } 119 | Foreach ($ds in $Datastore) { 120 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 121 | if ($ds.ExtensionData.Host) { 122 | $attachedHosts = $ds.ExtensionData.Host 123 | Foreach ($VMHost in $attachedHosts) { 124 | $hostview = Get-View $VMHost.Key 125 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 126 | Write-Host "Mounting VMFS Datastore $($DS.Name) on host $($hostview.Name)..." 127 | $StorageSys.MountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); 128 | } 129 | } 130 | } 131 | } 132 | } 133 | 134 | Function Attach-Datastore { 135 | [CmdletBinding()] 136 | Param ( 137 | [Parameter(ValueFromPipeline=$true)] 138 | $Datastore 139 | ) 140 | Process { 141 | if (-not $Datastore) { 142 | Write-Host "No Datastore defined as input" 143 | Exit 144 | } 145 | Foreach ($ds in $Datastore) { 146 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 147 | if ($ds.ExtensionData.Host) { 148 | $attachedHosts = $ds.ExtensionData.Host 149 | Foreach ($VMHost in $attachedHosts) { 150 | $hostview = Get-View $VMHost.Key 151 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 152 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 153 | Foreach ($device in $devices) { 154 | if ($device.canonicalName -eq $hostviewDSDiskName) { 155 | $LunUUID = $Device.Uuid 156 | Write-Host "Attaching LUN $($Device.CanonicalName) to host $($hostview.Name)..." 157 | $StorageSys.AttachScsiLun($LunUUID); 158 | } 159 | } 160 | } 161 | } 162 | } 163 | } 164 | } 165 | # 166 | #Get-Datastore | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 167 | # 168 | #Get-Datastore IX2ISCSI01 | Unmount-Datastore 169 | # 170 | #Get-Datastore IX2ISCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 171 | # 172 | #Get-Datastore IX2iSCSI01 | Mount-Datastore 173 | # 174 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 175 | # 176 | #Get-Datastore IX2iSCSI01 | Detach-Datastore 177 | # 178 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 179 | # 180 | #Get-Datastore IX2iSCSI01 | Attach-datastore 181 | # 182 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 183 | # -------------------------------------------------------------------------------- /Update_Tools/UpdateToolsbyHosts.ps1: -------------------------------------------------------------------------------- 1 | # Update VM-Tools on all Windows VMs in a datacenter 2 | # Created by: Zach Milleson 3 | # 4 | # Step 1 - Disable DRS on each cluster and gather VMs on individual hosts 5 | 6 | #Connect to vCenter 7 | Connect-VIServer -Server 144.210.196.99 -User "ipgna\esb.service" -Password Password1 8 | # Disable DRS on gen cluster 9 | Set-Cluster -Cluster "DRSEDC4" -DrsEnabled:$false -Confirm:$false 10 | # Disable DRS on SAP cluster 11 | Set-Cluster -Cluster "DRSSAP4" -DrsEnabled:$false -Confirm:$false 12 | 13 | #Gather VMs on the hosts 14 | $MyVMHosts = Get-Datacenter "DRSEDC" | Get-VMHost 15 | foreach ($line in $MyVMHosts) { 16 | #Retrieve guests on each host 17 | Get-VMHost -Name $line.name | get-vm | %{get-view $_.ID} | where {$_.guest.GuestFamily -eq "windowsGuest"} | select Name | export-csv D:\Script_Repo\CSVs\DRS\$line.csv 18 | } 19 | 20 | #Disconnect from vCenter 21 | Disconnect-VIServer -Confirm:$false 22 | 23 | 24 | #Step 2 - Connect to one host at a time and update tools on all Windows VMs 25 | 26 | Connect-VIServer -Server "144.210.196.101" -User root -Password "D1s@st3r" 27 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx001.ilo.interpublic.com.csv" 28 | foreach ($vm in $vms){ 29 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 30 | } 31 | Clear-Variable -Name vms -Force 32 | Disconnect-VIServer -Confirm:$false 33 | 34 | Start-Sleep -Seconds 480 35 | 36 | Connect-VIServer -Server "144.210.196.120" -User root -Password "D1s@st3r" 37 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx020.ilo.interpublic.com.csv" 38 | foreach ($vm in $vms){ 39 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 40 | } 41 | Clear-Variable -Name vms -Force 42 | Disconnect-VIServer -Confirm:$false 43 | 44 | Start-Sleep -Seconds 480 45 | 46 | Connect-VIServer -Server "144.210.196.102" -User root -Password "D1s@st3r" 47 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx002.ilo.interpublic.com.csv" 48 | foreach ($vm in $vms){ 49 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 50 | } 51 | Clear-Variable -Name vms -Force 52 | Disconnect-VIServer -Confirm:$false 53 | 54 | Connect-VIServer -Server "144.210.196.121" -User root -Password "D1s@st3r" 55 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx021.ilo.interpublic.com.csv" 56 | foreach ($vm in $vms){ 57 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 58 | } 59 | Clear-Variable -Name vms -Force 60 | Disconnect-VIServer -Confirm:$false 61 | 62 | Start-Sleep -Seconds 480 63 | 64 | Connect-VIServer -Server "144.210.196.103" -User root -Password "D1s@st3r" 65 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx003.ilo.interpublic.com.csv" 66 | foreach ($vm in $vms){ 67 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 68 | } 69 | Clear-Variable -Name vms -Force 70 | Disconnect-VIServer -Confirm:$false 71 | 72 | Start-Sleep -Seconds 480 73 | 74 | Connect-VIServer -Server "144.210.196.122" -User root -Password "D1s@st3r" 75 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx022.ilo.interpublic.com.csv" 76 | foreach ($vm in $vms){ 77 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 78 | } 79 | Clear-Variable -Name vms -Force 80 | Disconnect-VIServer -Confirm:$false 81 | 82 | Start-Sleep -Seconds 480 83 | 84 | Connect-VIServer -Server "144.210.196.104" -User root -Password "D1s@st3r" 85 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx004.ilo.interpublic.com.csv" 86 | foreach ($vm in $vms){ 87 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 88 | } 89 | Clear-Variable -Name vms -Force 90 | Disconnect-VIServer -Confirm:$false 91 | 92 | Start-Sleep -Seconds 480 93 | 94 | Connect-VIServer -Server "144.210.196.123" -User root -Password "D1s@st3r" 95 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx023.ilo.interpublic.com.csv" 96 | foreach ($vm in $vms){ 97 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 98 | } 99 | Clear-Variable -Name vms -Force 100 | Disconnect-VIServer -Confirm:$false 101 | 102 | Start-Sleep -Seconds 480 103 | 104 | Connect-VIServer -Server "144.210.196.105" -User root -Password "D1s@st3r" 105 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx005.ilo.interpublic.com.csv" 106 | foreach ($vm in $vms){ 107 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 108 | } 109 | Clear-Variable -Name vms -Force 110 | Disconnect-VIServer -Confirm:$false 111 | 112 | Start-Sleep -Seconds 480 113 | 114 | Connect-VIServer -Server "144.210.196.106" -User root -Password "D1s@st3r" 115 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx006.ilo.interpublic.com.csv" 116 | foreach ($vm in $vms){ 117 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 118 | } 119 | Clear-Variable -Name vms -Force 120 | Disconnect-VIServer -Confirm:$false 121 | 122 | Start-Sleep -Seconds 480 123 | 124 | Connect-VIServer -Server "144.210.196.107" -User root -Password "D1s@st3r" 125 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx007.ilo.interpublic.com.csv" 126 | foreach ($vm in $vms){ 127 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 128 | } 129 | Clear-Variable -Name vms -Force 130 | Disconnect-VIServer -Confirm:$false 131 | 132 | Start-Sleep -Seconds 480 133 | 134 | Connect-VIServer -Server "144.210.196.108" -User root -Password "D1s@st3r" 135 | $vms = Import-CSV "D:\Script_Repo\CSVs\DRS\drsedcvmx008.ilo.interpublic.com.csv" 136 | foreach ($vm in $vms){ 137 | Get-VM $vm.name | Update-Tools -NoReboot -RunAsync 138 | } 139 | Clear-Variable -Name vms -Force 140 | Disconnect-VIServer -Confirm:$false 141 | 142 | 143 | #Connect to vCenter 144 | Connect-VIServer -Server 144.210.196.99 -User "ipgna\esb.service" -Password Password1 145 | # Disable DRS on gen cluster 146 | Set-Cluster -Cluster "DRSEDC4" -DrsEnabled:$true -Confirm:$false 147 | # Disable DRS on SAP cluster 148 | Set-Cluster -Cluster "DRSSAP4" -DrsEnabled:$true -Confirm:$false 149 | Disconnect-VIServer -Confirm:$false -------------------------------------------------------------------------------- /Resource-Pool-Pie.ps1: -------------------------------------------------------------------------------- 1 | ################################################################################# 2 | # ResourcePoolPie 3 | # 4 | # This script will poll look at VMs residing in a production and a test resource 5 | # pool and determine how to best set the custom share value in order to maintian 6 | # a 4:1 Production:Test ratio. Note, you must be setup in a Production and Test 7 | # Environment inside of one cluster. Its kind of unique to my environment and 8 | # may not apply to everyone elses, but feel free to change and modify what you 9 | # need in order to make it work for you. 10 | # 11 | # The following variables will need to be assigned 12 | # 13 | # $vcenterserver = ip address of vcenter 14 | # $clustername = name of cluster containing resource pools 15 | # $prodname = name of production resource pool 16 | # $testname = name of test resource pool 17 | # 18 | # Created By: Mike Preston, 2011 19 | # 20 | # 21 | ################################################################################# 22 | 23 | 24 | Add-PSSnapin VMware.VimAutomation.Core 25 | 26 | # Assign appropriate values to following variables. 27 | $vcenterserver = Read-Host "Enter vcenter server (IP or DNS)" 28 | $clustername = Read-Host "Enter the cluster name" 29 | $prodname = "" 30 | $testname = "" 31 | 32 | # establish connection to vcenter server 33 | $connection = Connect-VIServer $vcenterserver 34 | 35 | # get cluster information 36 | $clus = get-Cluster -Name $clustername | get-view 37 | 38 | # get resource pool information 39 | $prodpool = Get-ResourcePool -Location $clustername -Name $prodname 40 | $testpool = Get-ResourcePool -Location $clustername -Name $testname 41 | 42 | # get a list of vms in production and test 43 | $prodvms = get-vm -Location $prodpool | where { $_.PowerState -eq "PoweredOn" } 44 | $testvms = get-vm -Location $testpool | where { $_.PowerState -eq "PoweredOn" } 45 | 46 | # initialize counters to zero 47 | $totalprodcpu = 0 48 | $totaltestcpu = 0 49 | $totalprodmem = 0 50 | $totaltestmem = 0 51 | 52 | # loop through production pool and total cpu/memory 53 | foreach ($vm in $prodvms) 54 | { 55 | $totalprodcpu = $totalprodcpu + $vm.NumCPU 56 | $totalprodmem = $totalprodmem + $vm.MemoryMB 57 | } 58 | 59 | # loop through test pool and total cpu/memory 60 | foreach ($vm in $testvms) 61 | { 62 | $totaltestcpu = $totaltestcpu + $vm.NumCPU 63 | $totaltestmem = $totaltestmem + $vm.MemoryMB 64 | } 65 | 66 | # Begin CPU calculations 67 | Write-Host "CPU Configuration" 68 | Write-Host "==========================================================" 69 | write-host "Production Pool contains" $prodvms.count "Powered On VMs containing" $totalprodcpu "cpus" 70 | write-host "Test Pool contains" $testvms.count "Powered On VMs containing" $totaltestcpu "cpus" 71 | write-host "Cluster has" $clus.summary.effectivecpu "MHZ to hand out" 72 | 73 | #populate variables for formula a(4w-3x) = nx 74 | 75 | $a = $totalprodcpu 76 | $w = $clus.summary.effectivecpu 77 | $n = $totalprodcpu + $totaltestcpu 78 | Write-Host "" 79 | # lets solve x :) 80 | Write-Host "Lets plug these numbers into our formula and solve x (Production Share)" 81 | Write-Host "a = total number in production, w = total resources, n = total number in prod and test" 82 | Write-Host "--------------------------------" 83 | Write-Host "a(4w-3x) = nx) " 84 | Write-Host "$a(4($w) - 3(x)) = $n(x)) " 85 | # lets get some tmp vars initialized 86 | $tmp1 = 4 * $w 87 | Write-Host "$a($tmp1 - 3x) = $n(x)" 88 | $tmp2 = $a * $tmp1 89 | $tmp3 = 3 * $a 90 | Write-Host "$tmp2 - $tmp3(x) = $n(x)" 91 | $tmp4 = $n + $tmp3 92 | Write-Host "$tmp4(x) = $tmp2" 93 | $prodpoolresources = $tmp2 / $tmp4 94 | Write-Host "x = $prodpoolresources" 95 | Write-Host "--------------------------------" 96 | $prodpoolresources = [Math]::Round($prodpoolresources,0) 97 | $testpoolresources = $w - $prodpoolresources 98 | $prodsharepercpu = $prodpoolresources / $totalprodcpu 99 | $prodsharepercpu = [Math]::Round($prodsharepercpu,0) 100 | $testsharepercpu = $testpoolresources / $totaltestcpu 101 | $testsharepercpu = [Math]::Round($testsharepercpu,0) 102 | 103 | # Display recommendations 104 | Write-Host "Recommended Share setting for production $prodpoolresources Mhz split between" $prodvms.count "Vms with" $totalprodcpu "cpus resulting in" $prodsharepercpu "Mhz per cpu" 105 | Write-Host "Recommended Share setting for test $testpoolresources Mhz split between" $testvms.count "Vms with" $totaltestcpu "cpus resulting in" $testsharepercpu "mhz per cpu" 106 | 107 | # Begin calculating Memory 108 | Write-Host "==========================================================" 109 | Write-Host "Memory Configuration" 110 | Write-Host "==========================================================" 111 | write-host "Production Pool contains" $prodvms.count "Powered On VMs containing" $totalprodmem "MB of Memory" 112 | write-host "Test Pool contains" $testvms.count "Powered On VMs containing" $totaltestmem "MB of Memory" 113 | write-host "Cluster has" $clus.summary.effectivememory "MB of memory to hand out" 114 | 115 | #populate variables for formula a(4w-3x) = nx 116 | 117 | $a = $totalprodmem 118 | $w = $clus.summary.effectivememory 119 | $n = $totalprodmem + $totaltestmem 120 | Write-Host "" 121 | # lets solve x :) 122 | Write-Host "Lets plug these numbers into our formula and solve x (Production Share)" 123 | Write-Host "--------------------------------" 124 | Write-Host "a(4w-3x) = nx) " 125 | Write-Host "$a(4($w) - 3(x)) = $n(x)) " 126 | # lets get some tmp vars initialized 127 | $tmp1 = 4 * $w 128 | Write-Host "$a($tmp1 - 3x) = $n(x)" 129 | $tmp2 = $a * $tmp1 130 | $tmp3 = 3 * $a 131 | Write-Host "$tmp2 - $tmp3(x) = $n(x)" 132 | $tmp4 = $n + $tmp3 133 | Write-Host "$tmp4(x) = $tmp2" 134 | $prodpoolresources = $tmp2 / $tmp4 135 | Write-Host "x = $prodpoolresources" 136 | Write-Host "--------------------------------" 137 | $prodpoolresources = [Math]::Round($prodpoolresources,0) 138 | $testpoolresources = $w - $prodpoolresources 139 | $prodsharepermb = $prodpoolresources / $totalprodmem 140 | $testsharepermb = $testpoolresources / $totaltestmem 141 | # Output results 142 | Write-Host "Recommended Share setting for production $prodpoolresources MB split between" $prodvms.count "Vms with" $totalprodmem " MB of RAM resulting in $prodsharepermb shares per MB" 143 | Write-Host "Recommended Share setting for test $testpoolresources MB split between" $testvms.count "Vms with" $totaltestmem " MB of RAM resulting $testsharepermb shares per MB" 144 | Write-Host "==========================================================" -------------------------------------------------------------------------------- /Get-NICAndFirmware.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .NOTES 3 | =========================================================================== 4 | Created with: SAPIEN Technologies, Inc., PowerShell Studio 2014 v4.1.65 5 | Created on: 10/17/2014 10:43 AM 6 | Created by: Jon Howe 7 | Filename: Get-NICAndFirmware.ps1 8 | =========================================================================== 9 | .SYNOPSIS 10 | Connects to VirtualCenter and lists pertinent NIC driver and version information 11 | .DESCRIPTION 12 | Connects to VirtualCenter and lists pertinent NIC driver and version information 13 | .PARAMETER $VirtualCenterServer 14 | Required String Parameter. The fully qualified domain name of the virtualcenter server 15 | .PARAMETER $cluster 16 | Optional StringParameter. The name of the cluster you want to filter by. 17 | .PARAMETER $asLocalUser 18 | Optional Boolean Parameter. Do you want to connect to vC as you, or do you want to manually 19 | authenticate as a different user 20 | .EXAMPLE 21 | Get-NicDriverAndFirmware -VirtualCenterServer vc-tst-1.test.in 22 | Actions Taken: 23 | This will connect to the specified virtualcenter server and list the driver name, version, 24 | and firmware version for every NIC in every host attached to your vCenter server. The script will 25 | authenticate to vCenter as your locally logged in user. 26 | Results: 27 | Host_Name VMNic_Name DriverName DriverVersion FirmwareVersion 28 | --------- ---------- ---------- ------------- --------------- 29 | ESXi-1.test.in.parata.local vmnic0 bnx2x 1.72.56.v55.2 bc 5.2.7 phy baa0.105 30 | ESXi-1.test.in.parata.local vmnic1 bnx2x 1.72.56.v55.2 bc 5.2.7 phy baa0.105 31 | ESXi-1.test.in.parata.local vmnic2 e1000e 1.1.2-NAPI 5.12-6 32 | ESXi-1.test.in.parata.local vmnic3 e1000e 1.1.2-NAPI 5.12-6 33 | ESXi-1.test.in.parata.local vmnic4 e1000e 1.1.2-NAPI 5.12-6 34 | ESXi-1.test.in.parata.local vmnic5 e1000e 1.1.2-NAPI 5.12-6 35 | .EXAMPLE 36 | Get-NicDriverAndFirmware -VirtualCenterServer vc-tst-1.test.in -ClusterName Production -asLocalUser $False | Format-Table -AutoSize 37 | Actions Taken: 38 | This will connect to the specified virtualcenter server and list the driver name, version, 39 | and firmware version for each NIC in every host in the cluster "Production", and will prompt for a username and password. 40 | Resuts: 41 | Same as example 1 42 | .EXAMPLE 43 | Get-NicDriverAndFirmware -VirtualCenterServer vc-tst-1.test.in -ClusterName Production -asLocalUser $False | c:\temp\vCenterInterfaceDriverandFirmware.csv -notypeinformation 44 | Actions Taken: 45 | This script outputs an object, so you can do anything you want with the output, such as create a CSV, sort, etc. 46 | Results: 47 | Sames as example 1 48 | 49 | .LINK 50 | Original Published Location 51 | http://www.cit3.net/vmware-powercli-gather-nic-driver-and-firmware-versions-from-hosts-via-vcenter 52 | .LINK 53 | VMware KB for gathering NIC Driver and Firmware versions 54 | http://kb.vmware.com/kb/1027206 55 | .LINK 56 | VMware Documentation on PowerCLI's Get-EsxCli commandlet 57 | http://pubs.vmware.com/vsphere-55/topic/com.vmware.powercli.cmdletref.doc/Get-EsxCli.html 58 | #> 59 | [CmdletBinding()] 60 | param ( 61 | [Parameter(Position = 0, Mandatory = $true)] 62 | [System.String] 63 | $VirtualCenterServer, 64 | [Parameter(Position = 1)] 65 | [System.String] 66 | $ClusterName, 67 | [Parameter(Position = 2)] 68 | [System.Boolean] 69 | $asLocalUser = $true 70 | ) 71 | 72 | #region Add Snapin and Connect to vC 73 | #Check to see if the VMware.VimAutomation.Core snapin is loaded - load it if it's not 74 | if ((Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) 75 | { 76 | Add-PsSnapin VMware.VimAutomation.Core 77 | } 78 | 79 | #Check to see if we're already connected to the correct VC Server 80 | if ($DefaultVIServers.name -ne $VirtualCenterServer) 81 | { 82 | #Determine if we're logging in to VirtualCenter as a local user or if we should prompt for credentials 83 | if ($asLocalUser) 84 | { 85 | Connect-VIServer -Server $VirtualCenterServer | Out-Null 86 | Write-Debug "Logging in as local user to vc: $VirtualCenterServer" 87 | } 88 | else 89 | { 90 | Connect-VIServer -Server $VirtualCenterServer -Credential (Get-Credential) | Out-Null 91 | Write-Debug "Logging in as manually selected user to vc: $VirtualCenterServer" 92 | } 93 | } 94 | else 95 | { 96 | Write-Debug "Looks like we're already connected to: $VirtualCenterServer in this session" 97 | } 98 | #endregion Add Snapin and Connect to vC 99 | 100 | #region Get List of Hosts 101 | if ($ClusterName) 102 | { 103 | $VMHosts = Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } 104 | } 105 | else 106 | { 107 | $VMhosts = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } 108 | } 109 | #endregion Get List of Hosts 110 | 111 | $results = @() 112 | foreach ($VMHost in $VMHosts) 113 | { 114 | #Get list of network interfaces on host 115 | $VMHostNetworkAdapters = Get-VMHost $VMHost | Get-VMHostNetworkAdapter | Where-Object { $_.Name -like "vmnic*" } 116 | 117 | $esxcli = Get-VMHost $VMHost | Get-EsxCli 118 | 119 | $arrNicDetail = @() 120 | foreach ($VMNic in $VMHostNetworkAdapters) 121 | { 122 | $objOneNic = New-Object System.Object 123 | $objDriverInfo = ($esxcli.network.nic.get($VMNic.Name)).DriverInfo 124 | 125 | $objOneNic | Add-Member -type NoteProperty -name Host_Name -Value $VMHost.Name 126 | $objOneNic | Add-Member -type NoteProperty -name VMNic_Name -Value $VMNic.Name 127 | $objOneNic | Add-Member -type NoteProperty -name DriverName -Value $objDriverInfo.Driver 128 | $objOneNic | Add-Member -type NoteProperty -name DriverVersion -Value $objDriverInfo.Version 129 | $objOneNic | Add-Member -type NoteProperty -name FirmwareVersion -Value $objDriverInfo.FirmwareVersion 130 | $arrNicDetail += $objOneNic 131 | } 132 | 133 | $results += $arrNicDetail 134 | } 135 | 136 | $results 137 | Disconnect-VIServer -Server $VirtualCenterServer -Confirm:$false 138 | Remove-PSSnapin VMware.VimAutomation.Core 139 | -------------------------------------------------------------------------------- /Power-Off-VMs.ps1: -------------------------------------------------------------------------------- 1 | ################################################################################# 2 | # Power off VMs (poweroffvms.ps1) 3 | # 4 | # This is a complete update to my previous shutdown script. No longer do we 5 | # loop through the esx hosts and shut down VMs per host. We now just shut them 6 | # all down up front. Also, no more $vmstoleaveon variable. I'm assuming here 7 | # that your vCenter is not virtual. If it is you can most likely grab version 8 | # 1 of this script and take the code to leave the vCenter host till last. Maybe 9 | # someday I'll get around to updating it to merge the two...but for now, this is 10 | # it! 11 | # 12 | # This script does have a 'partner' script that powers the VMs back on, you can 13 | # grab that script at http://blog.mwpreston.net/shares/ 14 | # 15 | # Created By: Mike Preston, 2012 - With a whole lot of help from Eric Wright 16 | # (@discoposse) 17 | # 18 | # Variables: $mysecret - a secret word to actually make the script run, stops 19 | # the script from running when double click DISASTER 20 | # $vcenter - The IP/DNS of your vCenter Server 21 | # $username/password - credentials for your vCenter Server 22 | # $filename - path to csv file to store powered on vms 23 | # used for the poweronvms.ps1 script. 24 | # $cluster - Name of specific cluster to target within vCenter 25 | # $datacenter - Name of specific datacenter to target within vCenter 26 | # 27 | # 28 | # Usage: ./poweroffvms.ps1 "keyword" 29 | # Intended to be ran in the command section of the APC Powerchute Network 30 | # Shutdown program before the shutdown sequence has started. 31 | # 32 | ################################################################################# 33 | 34 | param($keyword) 35 | 36 | Add-PSSnapin VMware.VimAutomation.Core 37 | #some variables 38 | $vcenter = "vcenterServer" 39 | $username = "user" 40 | $password = "password" 41 | $cluster = "clusterName" 42 | $datacenter = "datacenterName" 43 | $filename = "c:\path\to\poweredonvms.csv" 44 | $mysecret = "kerfuffle" 45 | 46 | Write-Host "A Powerchute network shutdown command has been sent to the vCenter Server." -Foregroundcolor yellow 47 | Write-Host "This script will shutdown all of the VMs and hosts located in $datacenter" -Foregroundcolor yellow 48 | Write-Host "Upon completion, this server ($vcenter) will also be shutdown gracefully" -Foregroundcolor yellow 49 | Write-Host "" 50 | Write-Host "This script has also has a counterpart (powervmsbackon.ps1) which should" -Foregroundcolor yellow 51 | Write-Host "be setup to run during the startup of this machine ($vcenter). " -Foregroundcolor yellow 52 | Write-Host "This will ensure that your VMs are powered back on once power is restored!" -Foregroundcolor yellow 53 | Sleep 5 54 | 55 | if ($keyword -ne $mysecret) 56 | { 57 | Write-Host "You haven't passed the proper detonation sequence...ABORTING THE SCRIPT" -ForegroundColor red 58 | exit 59 | } 60 | 61 | #connect to vcenter 62 | Write-Host "Connecting to vCenter - $vcenter ...." -nonewline 63 | $success = Connect-VIServer $vcenter -username $username -Password $password 64 | if ($success) { Write-Host "Connected!" -Foregroundcolor Green } 65 | else 66 | { 67 | Write-Host "Something is wrong, Aborting script" -Foregroundcolor Red 68 | exit 69 | } 70 | Write-Host "" 71 | 72 | 73 | #Get a list of all powered on VMs - used for powering back on.... 74 | Get-VM -Location $cluster | where-object {$_.PowerState -eq "PoweredOn" } | Select Name | Export-CSV $filename 75 | 76 | #change DRS Automation level to partially automated... 77 | Write-Host "Changing cluster DRS Automation Level to Partially Automated" -Foregroundcolor green 78 | Get-Cluster $cluster | Set-Cluster -DrsAutomation PartiallyAutomated -confirm:$false 79 | #change the HA Level 80 | Write-Host "" 81 | Write-Host "Disabling HA on the cluster..." -Foregroundcolor green 82 | Write-Host "" 83 | Get-Cluster $cluster | Set-Cluster -HAEnabled:$false -confirm:$false 84 | 85 | #get VMs again (we will do this again instead of parsing the file in case a VM was powered in the nanosecond that it took to get here.... :) 86 | Write-Host "" 87 | Write-Host "Retrieving a list of powered on guests...." -Foregroundcolor Green 88 | Write-Host "" 89 | $poweredonguests = Get-VM -Location $cluster | where-object {$_.PowerState -eq "PoweredOn" } 90 | 91 | #and now, let's start powering off some guests.... 92 | ForEach ( $guest in $poweredonguests ) 93 | { 94 | Write-Host "Processing $guest ...." -ForegroundColor Green 95 | Write-Host "Checking for VMware tools install" -Foregroundcolor Green 96 | $guestinfo = get-view -Id $guest.ID 97 | if ($guestinfo.config.Tools.ToolsVersion -eq 0) 98 | { 99 | Write-Host "No VMware tools detected in $guest , hard power this one" -ForegroundColor Yellow 100 | Stop-VM $guest -confirm:$false 101 | } 102 | else 103 | { 104 | write-host "VMware tools detected. I will attempt to gracefully shutdown $guest" 105 | $vmshutdown = $guest | shutdown-VMGuest -Confirm:$false 106 | } 107 | } 108 | 109 | #Lets wait a minute or so for shutdowns to complete 110 | Write-Host "" 111 | Write-Host "Giving VMs 2 minutes before resulting in hard poweroff" 112 | Write-Host "" 113 | Sleep 120 114 | 115 | 116 | #Now, let's go back through again to see if anything is still powered on and shut it down if it is 117 | Write-Host "Beginning Phase 2 - anything left on....night night..." -ForegroundColor red 118 | Write-Host "" 119 | #get our list of guests still powered on... 120 | $poweredonguests = Get-VM -Location $cluster | where-object {$_.PowerState -eq "PoweredOn" } 121 | ForEach ( $guest in $poweredonguests ) 122 | { 123 | Write-Host "Processing $guest ...." -ForegroundColor Green 124 | #no checking for toosl, we just need to blast it down... 125 | write-host "Shutting down $guest - I don't care, it just needs to be off..." -ForegroundColor Yellow 126 | Stop-VM $guest -confirm:$false 127 | } 128 | 129 | #wait 30 seconds 130 | Write-Host "Waiting 30 seconds and then proceding with host power off" 131 | Write-Host "" 132 | Sleep 30 133 | 134 | #and now its time to slam down the hosts - I've chosen to go by datacenter here but you could put the cluster 135 | # There are some standalone hosts in the datacenter that I would also like to shutdown, those vms are set to 136 | # start and stop with the host, so i can just shut those hosts down and they will take care of the vm shutdown ;) 137 | 138 | $esxhosts = Get-VMHost -Location $cluster 139 | foreach ($esxhost in $esxhosts) 140 | { 141 | #Shutem all down 142 | Write-Host "Shutting down $esxhost" -ForegroundColor Green 143 | $esxhost | Foreach {Get-View $_.ID} | Foreach {$_.ShutdownHost_Task($TRUE)} 144 | } -------------------------------------------------------------------------------- /Detach-RDM-from-Host.ps1: -------------------------------------------------------------------------------- 1 | ##################################### 2 | ## Setting up Datastore Functions ## 3 | ##################################### 4 | 5 | Function Get-DatastoreMountInfo { 6 | [CmdletBinding()] 7 | Param ( 8 | [Parameter(ValueFromPipeline=$true)] 9 | $Datastore 10 | ) 11 | Process { 12 | $AllInfo = @() 13 | if (-not $Datastore) { 14 | $Datastore = Get-Datastore 15 | } 16 | Foreach ($ds in $Datastore) { 17 | if ($ds.ExtensionData.info.Vmfs) { 18 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].diskname 19 | if ($ds.ExtensionData.Host) { 20 | $attachedHosts = $ds.ExtensionData.Host 21 | Foreach ($VMHost in $attachedHosts) { 22 | $hostview = Get-View $VMHost.Key 23 | $hostviewDSState = $VMHost.MountInfo.Mounted 24 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 25 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 26 | Foreach ($device in $devices) { 27 | $Info = "" | Select Datastore, VMHost, Lun, Mounted, State 28 | if ($device.canonicalName -eq $hostviewDSDiskName) { 29 | $hostviewDSAttachState = "" 30 | if ($device.operationalState[0] -eq "ok") { 31 | $hostviewDSAttachState = "Attached" 32 | } elseif ($device.operationalState[0] -eq "off") { 33 | $hostviewDSAttachState = "Detached" 34 | } else { 35 | $hostviewDSAttachState = $device.operationalstate[0] 36 | } 37 | $Info.Datastore = $ds.Name 38 | $Info.Lun = $hostviewDSDiskName 39 | $Info.VMHost = $hostview.Name 40 | $Info.Mounted = $HostViewDSState 41 | $Info.State = $hostviewDSAttachState 42 | $AllInfo += $Info 43 | } 44 | } 45 | 46 | } 47 | } 48 | } 49 | } 50 | $AllInfo 51 | } 52 | } 53 | 54 | Function Detach-Datastore { 55 | [CmdletBinding()] 56 | Param ( 57 | [Parameter(ValueFromPipeline=$true)] 58 | $Datastore 59 | ) 60 | Process { 61 | if (-not $Datastore) { 62 | Write-Host "No Datastore defined as input" 63 | Exit 64 | } 65 | Foreach ($ds in $Datastore) { 66 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 67 | if ($ds.ExtensionData.Host) { 68 | $attachedHosts = $ds.ExtensionData.Host 69 | Foreach ($VMHost in $attachedHosts) { 70 | $hostview = Get-View $VMHost.Key 71 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 72 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 73 | Foreach ($device in $devices) { 74 | if ($device.canonicalName -eq $hostviewDSDiskName) { 75 | $LunUUID = $Device.Uuid 76 | Write-Host "Detaching LUN $($Device.CanonicalName) from host $($hostview.Name)..." 77 | $StorageSys.DetachScsiLun($LunUUID); 78 | } 79 | } 80 | } 81 | } 82 | } 83 | } 84 | } 85 | 86 | Function Unmount-Datastore { 87 | [CmdletBinding()] 88 | Param ( 89 | [Parameter(ValueFromPipeline=$true)] 90 | $Datastore 91 | ) 92 | Process { 93 | if (-not $Datastore) { 94 | Write-Host "No Datastore defined as input" 95 | Exit 96 | } 97 | Foreach ($ds in $Datastore) { 98 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 99 | if ($ds.ExtensionData.Host) { 100 | $attachedHosts = $ds.ExtensionData.Host 101 | Foreach ($VMHost in $attachedHosts) { 102 | $hostview = Get-View $VMHost.Key 103 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 104 | Write-Host "Unmounting VMFS Datastore $($DS.Name) from host $($hostview.Name)..." 105 | $StorageSys.UnmountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); 106 | } 107 | } 108 | } 109 | } 110 | } 111 | 112 | Function Mount-Datastore { 113 | [CmdletBinding()] 114 | Param ( 115 | [Parameter(ValueFromPipeline=$true)] 116 | $Datastore 117 | ) 118 | Process { 119 | if (-not $Datastore) { 120 | Write-Host "No Datastore defined as input" 121 | Exit 122 | } 123 | Foreach ($ds in $Datastore) { 124 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 125 | if ($ds.ExtensionData.Host) { 126 | $attachedHosts = $ds.ExtensionData.Host 127 | Foreach ($VMHost in $attachedHosts) { 128 | $hostview = Get-View $VMHost.Key 129 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 130 | Write-Host "Mounting VMFS Datastore $($DS.Name) on host $($hostview.Name)..." 131 | $StorageSys.MountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); 132 | } 133 | } 134 | } 135 | } 136 | } 137 | 138 | Function Attach-Datastore { 139 | [CmdletBinding()] 140 | Param ( 141 | [Parameter(ValueFromPipeline=$true)] 142 | $Datastore 143 | ) 144 | Process { 145 | if (-not $Datastore) { 146 | Write-Host "No Datastore defined as input" 147 | Exit 148 | } 149 | Foreach ($ds in $Datastore) { 150 | $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname 151 | if ($ds.ExtensionData.Host) { 152 | $attachedHosts = $ds.ExtensionData.Host 153 | Foreach ($VMHost in $attachedHosts) { 154 | $hostview = Get-View $VMHost.Key 155 | $StorageSys = Get-View $HostView.ConfigManager.StorageSystem 156 | $devices = $StorageSys.StorageDeviceInfo.ScsiLun 157 | Foreach ($device in $devices) { 158 | if ($device.canonicalName -eq $hostviewDSDiskName) { 159 | $LunUUID = $Device.Uuid 160 | Write-Host "Attaching LUN $($Device.CanonicalName) to host $($hostview.Name)..." 161 | $StorageSys.AttachScsiLun($LunUUID); 162 | } 163 | } 164 | } 165 | } 166 | } 167 | } 168 | } 169 | # 170 | #Get-Datastore | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 171 | # 172 | #Get-Datastore IX2ISCSI01 | Unmount-Datastore 173 | # 174 | #Get-Datastore IX2ISCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 175 | # 176 | #Get-Datastore IX2iSCSI01 | Mount-Datastore 177 | # 178 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 179 | # 180 | #Get-Datastore IX2iSCSI01 | Detach-Datastore 181 | # 182 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 183 | # 184 | #Get-Datastore IX2iSCSI01 | Attach-datastore 185 | # 186 | #Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize 187 | # 188 | 189 | ##################################################### 190 | # Done setting up functions # 191 | ##################################################### 192 | <# 193 | #Get-VM | Get-HardDisk -DiskType “RawPhysical”,”RawVirtual” | Select Parent,Name,DiskType,ScsiCanonicalName,DeviceName #| fl > output.txt 194 | 195 | #$cluster = OMAEDC 196 | $cluster = "Test-Cluster" 197 | #Get-Cluster $cluster | Get-VMHost | Get-ScsiLun | Select {$_.CanonicalName} 198 | 199 | $targetStorage = Get-Cluster $cluster | Get-VMHost | Get-ScsiLun | Select CanonicalName 200 | 201 | Write-Host "" 202 | 203 | #$targetStorage 204 | 205 | Write-Host "" 206 | #> 207 | 208 | # EXAMPLE NAA ID = "naa.50002ac003c80dbb" 209 | 210 | $naaID = Read-Host "Paste the naa id here" 211 | #$cluster = "OMAEDC" 212 | $cluster = "Test-Cluster" 213 | $vmHosts = Get-Cluster $cluster | Get-VMHost 214 | $canonicalNames = $vmHosts | Get-ScsiLun 215 | $targetLUN = ($canonicalNames | Where {$_.CanonicalName -eq $naaID}) 216 | 217 | $canonicalNames 218 | Write-Host "" 219 | 220 | $targetLUN | Select CanonicalName 221 | 222 | Get-Datastore 223 | 224 | #$vmHosts | Get-Datastore | Get-DatastoreMountInfo | Select Lun #| Sort Datastore, VMHost | FT -AutoSize 225 | 226 | -------------------------------------------------------------------------------- /ESXi-Set-NTP.ps1: -------------------------------------------------------------------------------- 1 | <###################################################################### 2 | Menu-driven PowerCLI script to delete, add, and update DNS and NTP on 3 | VMware ESXi hosts. 4 | **Save as set-ntp.ps1 5 | **Switch to directory ps1 is saved in and run 6 | ** MAKE SURE LOCAL SYSTEM TIME IS CORRECT!!!! 7 | v1.0 27 February 2014: Initial draft 8 | v1.1 27 February 2014: Changed menu option 1 to dark gray cause no worky. 9 | Written By Josh Townsend 10 | All Code provided as is and used at your own risk. 11 | ######################################################################> 12 | $xAppName = "set-ntpd" 13 | [BOOLEAN]$global:xExitSession=$false 14 | 15 | # Add PowerCLI snapin if not already loaded 16 | if ((Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) {Add-PsSnapin VMware.VimAutomation.Core; $bSnapinAdded = $true} 17 | 18 | # Prompt for vCenter or ESXi server 19 | $vCenter = Read-host "Enter the name of your vCenter Server or ESXi host" 20 | $domain = Read-host "Domain name (leave blank if using local ESXi account)" 21 | $user = Read-host "vCenter or ESXi user account" 22 | $password = Read-host -Prompt "Enter password" -AsSecureString 23 | $decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)) 24 | Connect-VIServer $vCenter -user $domain\$user -Password $decodedpassword 25 | 26 | #Some other connection options: 27 | #Option 1 - Show menu of recently used ESXi or vCenter Servers 28 | #Write-host "Choose from the list below or enter the name of your vCenter Server or ESXi Host, then enter credentials as prompted" -ForegroundColor Yellow 29 | #Connect-VIServer -Menu $true 30 | #option 2 - Hard code it. This leaves your password in plain text. Consider using the new-VICredentialStore option to securely store your credentials! 31 | #Connect-VIServer -Server 10.10.10.10 -User root -Password vmware 32 | 33 | $esxHosts = get-VMHost 34 | 35 | Function Clear-DNS{ 36 | #foreach ($esx in $esxHosts) #{ 37 | #Write-Host "Deleting existing DNS servers from $esx" -ForegroundColor Green 38 | # Get Current Values for required properties 39 | #$currenthostname = Get-VMHost | Get-VMHostNetwork | select hostname 40 | #$currentdomainName = Get-VMHost | Get-VMHostNetwork | select domainname 41 | 42 | # ------- UpdateDnsConfig ------- 43 | #$config = New-Object VMware.Vim.HostDnsConfig 44 | #$config.dhcp = $false 45 | #$config.hostName = $currenthostname 46 | #$config.domainName = $domainname 47 | 48 | #$_this = Get-View -Id 'HostNetworkSystem-networkSystem' 49 | #$_this.UpdateDnsConfig($config) 50 | #} 51 | #Write-Host "Old DNS Values Cleared! Press any key to return to menu..." -ForegroundColor Green 52 | Write-Host "Sorry, this function not supported because we cannot delete or write null values for DNS Server Addresses using PowerCLI. `nUse the Add Additional menu option to overwrite existing DNS servers. `nPress any key to return to the menu." -ForegroundColor Magenta 53 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 54 | LoadMenuSystem 55 | } 56 | 57 | Function Clear-NTP{ 58 | foreach ($esx in $esxHosts) { 59 | Write-Host "Deleting existing NTP servers from $esx" -ForegroundColor Green 60 | $existingNTParray = $esxhosts | Get-VMHostNTPServer 61 | Remove-VMHostNTPServer -NtpServer $existingNTParray -Confirm:$false 62 | } 63 | Write-Host "Old NTP Values Cleared! Press any key to return to menu..." -ForegroundColor Green 64 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 65 | LoadMenuSystem 66 | } 67 | 68 | Function Clear-NTPDNS{ 69 | Clear-NTP 70 | Clear-DNS 71 | 72 | Write-Host "Done! Press any key to return to menu...." -ForegroundColor Green 73 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 74 | LoadMenuSystem 75 | } 76 | 77 | Function Manual-Time{ 78 | # First set all hosts in vCenter to use time of local system to prevent too large drift for NTP to correct 79 | Write-Host "Updating manual time on $esx to match local system time" -ForegroundColor Green 80 | $esxhosts | Where-Object { 81 | $t = Get-Date 82 | $dst = $_ | %{ Get-View $_.ExtensionData.ConfigManager.DateTimeSystem } 83 | $dst.UpdateDateTime((Get-Date($t.ToUniversalTime()) -format u)) 84 | } 85 | Write-Host "Done! Press any key to return to menu...." -ForegroundColor Green 86 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 87 | LoadMenuSystem 88 | } 89 | 90 | Function Set-DNS{ 91 | # Prompt for Primary and Alternate DNS Servers 92 | $dnspri = read-host "Enter Primary DNS" 93 | $dnsalt = read-host "Enter Alternate DNS" 94 | 95 | # Prompt for Domain 96 | $domainname = read-host "Enter Domain Name" 97 | 98 | foreach ($esx in $esxHosts) { 99 | 100 | Write-Host "Configuring DNS and Domain Name on $esx" -ForegroundColor Green 101 | Get-VMHostNetwork -VMHost $esx | Set-VMHostNetwork -DomainName $domainname -DNSAddress $dnspri , $dnsalt -Confirm:$false 102 | 103 | Write-Host "Done! Press any key to return to menu...." -ForegroundColor Green 104 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 105 | LoadMenuSystem 106 | } 107 | } 108 | 109 | Function Set-NTP{ 110 | 111 | #Prompt for NTP Servers 112 | $ntpone = read-host "Enter NTP Server One" 113 | $ntptwo = read-host "Enter NTP Server Two" 114 | 115 | foreach ($esx in $esxHosts) { 116 | 117 | Write-Host "Configuring NTP Servers on $esx" -ForegroundColor Green 118 | Add-VMHostNTPServer -NtpServer $ntpone , $ntptwo -VMHost $esx -Confirm:$false 119 | 120 | Write-Host "Allow NTP queries outbound through the firewall on $esx" -ForegroundColor Green 121 | Get-VMHostFirewallException -VMHost $esx | where {$_.Name -eq "NTP client"} | Set-VMHostFirewallException -Enabled:$true 122 | 123 | Write-Host "Starting NTP service on $esx" -ForegroundColor Green 124 | Get-VmHostService -VMHost $esx | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService 125 | 126 | Write-Host "Configuring NTP Client Policy on $esx" -ForegroundColor Green 127 | Get-VMHostService -VMHost $esx | where{$_.Key -eq "ntpd"} | Set-VMHostService -policy "on" -Confirm:$false 128 | 129 | Write-Host "Restarting NTP Client on $esx" -ForegroundColor Green 130 | Get-VMHostService -VMHost $esx | where{$_.Key -eq "ntpd"} | Restart-VMHostService -Confirm:$false 131 | } 132 | Write-Host "Done! Press any key to return to menu...." -ForegroundColor Green 133 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 134 | LoadMenuSystem 135 | } 136 | 137 | Function Set-NTPDNS { 138 | Set-DNS 139 | Set-NTP 140 | 141 | Write-Host "Done! Press any key to return to menu...." -ForegroundColor Green 142 | $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 143 | LoadMenuSystem 144 | } 145 | 146 | # Menu to select functions 147 | function LoadMenuSystem() { 148 | [int]$xMenuChoiceA = 0 149 | [BOOLEAN]$xValidSelection=$false 150 | while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 8 ){ 151 | CLS 152 | # ------ Menu Choices ------- 153 | Write-Host “Choose an option below to modify all ESXi hosts DNS and NTP settings.`n” -ForegroundColor Magenta 154 | Write-host "`t1. Delete all existing DNS Servers values (not working)" -ForegroundColor DarkGray 155 | Write-host "`t2. Delete all existing NTP Server values" -ForegroundColor Cyan 156 | Write-host "`t3. Delete all existing DNS & NTP Servers (not working)" -ForegroundColor Cyan 157 | Write-host "`t4. Manually set time on all hosts to match your local system time.*" -ForegroundColor Cyan 158 | Write-host "`t*This option prevents NTP sync problems due to large offset" -ForegroundColor Gray 159 | Write-host "`t5. Add additional DNS Server values**" -ForegroundColor Cyan 160 | Write-host "`t**This will overwrite any existing values" -ForegroundColor Gray 161 | Write-host "`t6. Add additional NTP Server values and set NTP to start with host.***" -ForegroundColor Cyan 162 | Write-host "`t***Verifyr DNS values are correct if using names instead of IPs." -ForegroundColor Gray 163 | Write-host "`t7. Add both NTP & DNS Server values and set NTP to start wtih host" -ForegroundColor Cyan 164 | Write-host "`t8. Quit and exit`n`n" -ForegroundColor Yellow 165 | # ------ Menu Choices ------- 166 | # Get and Validate Choice 167 | [Int]$xMenuChoiceA = read-host "Please select an option [1-8]" 168 | if( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 8 ){ 169 | Write-Host “`tInvalid Selection.`n” -Fore Red;start-Sleep -Seconds 1 170 | } 171 | 172 | # Survey Says.... 173 | 174 | Switch( $xMenuChoiceA ){#… User has selected a valid entry.. load menu 175 | 1{ Clear-DNS } 176 | 2{ Clear-NTP } 177 | 3{ Clear-NTPDNS } 178 | 4{ Manual-Time } 179 | 5{ Set-DNS } 180 | 6{ Set-NTP } 181 | 7{ set-NTPDNS } 182 | default { $global:xExitSession=$true;break } 183 | } 184 | } 185 | } 186 | 187 | 188 | LoadMenuSystem 189 | If ($xExitSession){ 190 | Exit-PSSession #… User quit & Exit 191 | } Else { 192 | .\set-ntp.ps1 #… Loop the function 193 | } -------------------------------------------------------------------------------- /CPReport-v2.1-Community-Edition.ps1: -------------------------------------------------------------------------------- 1 | ############################# INFORMATION ####################################### 2 | # VMWare Capacity & Performance Report 3 | # Marc Vincent Davoli (Find me on LinkedIn! http://ca.linkedin.com/in/marcvincentdavoli/) 4 | # PREREQUISITES for this script: Powershell V2, PowerCLI 5.0, Microsoft Chart Controls for .NET Framework (download from this link: 5 | # http://www.microsoft.com/en-us/download/details.aspx?id=14422) 6 | # INPUT for this script: vCenter server IP/hostname, vCenter server credentials, SMTP server IP/hostname 7 | # OUTPUT for this script: E-mailed Report, Report.HTML and Attachments, 1 for each chart (in the working directory) 8 | # Notice 1 : CPU and Memory provisioning potential is calculated by removing 1 host 9 | # Notice 2 : Datastore space provisioning potential is calculated by removing removing 5% 10 | 11 | 12 | ############################# CHANGELOG ####################################### 13 | # February 2013 First version 14 | # April 2013 Bugfixes, Added Per Cluster report 15 | # July 2013 Bugfixes, Added Cluster Resilience & Provisionning Potential reports, other minor code adjustements 16 | # January 2014 Added Consolidation ratio, ESXi Hardware & Software Information table, vCenter version, Print Computer name and script version 17 | # May 2015 Fixed issue with Cluster charts not appearing in e-mail report, cause by a space in the cluster name 18 | 19 | ################################ CONSTANTS ###################################### 20 | 21 | Write-Host Loading... 22 | 23 | #-------------------------CHANGE THESE VALUES-------------------------------- 24 | $SMTPServer = "omaedcmgw002.interpublic.com" #"webmail.interpublic.com" 25 | $vCenterServerName = "test-vcsa6" 26 | $ToAddress = "andru.estes@interpublic.com" 27 | #$ToAddress = "destinationadress1@company.com", "destinationadress2@company.com", "destinationadress3@company.com" 28 | #----------------------------------------------------------------------------- 29 | 30 | $ScriptVersion = "v2.1 - Community Edition" # Included in the Runtime info in $HTMLFooter 31 | $Subject = "VMware Capacity & Performance Report for " + $vCenterServerName 32 | #$FromAddress = $vCenterServerName + "@interpublic.com" 33 | $FromAddress = "andru.estes@interpublic.com" 34 | 35 | $ColorArray = "Red", "Orange", "Purple", "Blue", "Olive", "SlateGrey", "Orange", "Purple", "Blue", "Olive" 36 | $ColorArrayIndex = 0 37 | 38 | $HTMLHeader = " VMware Capacity & Performance Report for " + $vCenterServerName + "" 39 | $HTMLFooter = "Made with CPReport Script Version " + $ScriptVersion + " running on server " + $env:COMPUTERNAME + "" 40 | 41 | ############################# GLOBAL VARIABLES #################################### 42 | 43 | $global:ArrayOfNames = @() 44 | $global:ArrayOfValues = @() 45 | $Attachments = @() 46 | 47 | 48 | ############################## PREPROCESSING #################################### 49 | 50 | Write-Host Preprocessing... 51 | 52 | # Create a folder for temporary image files 53 | #IF ((Test-Path -path .\Temp) -ne $True) {$TempFolder = New-Item .\Temp -type directory} else {$TempFolder = ".\Temp"} 54 | 55 | 56 | Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue 57 | Connect-VIServer $vCenterServerName 58 | 59 | $DC = Get-Datacenter | Sort-Object -Property Name #| Select-Object -First 2 60 | $Clusters = Get-Cluster | Sort-Object -Property Name #| Select-Object -First 1 61 | $VMHosts = Get-VMHost | Sort-Object -Property Name #| Select-Object -First 1 62 | $VM = Get-VM | Sort-Object -Property Name #| Select-Object -First 2 63 | $Datastores = Get-Datastore | Sort-Object -Property Name #| Select-Object -First 1 64 | $Templates = Get-Template | Sort-Object -Property Name #| Select-Object -First 2 65 | $ResourcePools = Get-ResourcePool | Sort-Object -Property Name #| Select-Object -First 2 66 | $Snapshots = $VM | Get-Snapshot #| Select-Object -First 2 67 | $Date = Get-Date | Sort-Object -Property Name #| Select-Object -First 2 68 | 69 | ################################ FUNCTIONS ###################################### 70 | 71 | Function GetTotalCPUCyclesInGhz ($VMHostsTemp) { 72 | 73 | $TotalCPUCyclesInGHz = $VMHostsTemp | Measure-Object -Property CpuTotalMhz -Sum # Count total CPU in Mhz 74 | $TotalCPUCyclesInGHz = $TotalCPUCyclesInGHz.Sum -as [int] # Convert from String to Int 75 | $TotalCPUCyclesInGHz = $TotalCPUCyclesInGHz / 1000 # Divide by 1000 to convert from MHz to GHz 76 | $TotalCPUCyclesInGHz = [system.math]::ceiling($TotalCPUCyclesInGHz) # Round down 77 | return $TotalCPUCyclesInGHz 78 | } 79 | 80 | Function GetTotalNumberofCPUs ($VMHostsTemp){ 81 | 82 | $TotalCPU = $VMHostsTemp | Measure-Object -Property NumCpu -Sum # Count total RAM in MB 83 | $TotalCPU = $TotalCPU.Sum 84 | return $TotalCPU 85 | } 86 | 87 | Function GetTotalMemoryInGB ($VMHostsTemp){ 88 | 89 | $TotalRAMinGB = $VMHostsTemp | Measure-Object -Property MemoryTotalMB -Sum # Count total RAM in MB 90 | $TotalRAMinGB = $TotalRAMinGB.Sum -as [int] # Convert from String to Int 91 | $TotalRAMinGB = $TotalRAMinGB / 1024 # Divide by 1024 to convert from MB to GB 92 | $TotalRAMinGB = [system.math]::ceiling($TotalRAMinGB) # Round down 93 | return $TotalRAMinGB 94 | } 95 | 96 | Function GetTotalDatastoreDiskSpaceinGB ($DatastoresTemp) { 97 | 98 | $TotalDatastoreDiskSpaceinGB = $DatastoresTemp | Measure-Object -Property FreeSpaceMB -Sum # Count total MB 99 | $TotalDatastoreDiskSpaceinGB = $TotalDatastoreDiskSpaceinGB.Sum -as [int] # Convert from String to Int 100 | $TotalDatastoreDiskSpaceinGB = $TotalDatastoreDiskSpaceinGB / 1024 # Divide by 1024 to convert from MB to GB 101 | $TotalDatastoreDiskSpaceinGB = [system.math]::ceiling($TotalDatastoreDiskSpaceinGB) # Round down 102 | return $TotalDatastoreDiskSpaceinGB 103 | } 104 | 105 | 106 | Function GetVMHostMemoryinGB ($vmhosttemp){ 107 | 108 | $TempVMHostRAMinGB = $vmhosttemp.MemoryTotalMB -as [int] # Convert from String to Int 109 | $TempVMHostRAMinGB = $TempVMHostRAMinGB / 1024 # Divide by 1024 to convert from MB to GB 110 | $TempVMHostRAMinGB = [system.math]::ceiling($TempVMHostRAMinGB) # Round down 111 | return $TempVMHostRAMinGB 112 | } 113 | 114 | Function GetVMHostAverageCPUUsagePercentage ($vmhosttemp) { #For the last 30 days 115 | 116 | $AverageCPUUsagePercentage = Get-Stat -Entity ($vmhosttemp)-start (get-date).AddDays(-30) -Finish (Get-Date)-MaxSamples 31 -stat cpu.usage.average 117 | $AverageCPUUsagePercentage = $AverageCPUUsagePercentage | Measure-Object -Property value -Average 118 | $AverageCPUUsagePercentage = $AverageCPUUsagePercentage.Average 119 | $AverageCPUUsagePercentage = [system.math]::ceiling($AverageCPUUsagePercentage) # Round up 120 | return $AverageCPUUsagePercentage 121 | } 122 | 123 | Function GetVMHostAverageMemoryUsagePercentage ($vmhosttemp) { #For the last 30 days 124 | 125 | $AverageMemoryUsagePercentage = Get-Stat -Entity ($vmhosttemp)-start (get-date).AddDays(-30) -Finish (Get-Date)-MaxSamples 31 -stat mem.usage.average 126 | $AverageMemoryUsagePercentage = $AverageMemoryUsagePercentage | Measure-Object -Property value -Average 127 | $AverageMemoryUsagePercentage = $AverageMemoryUsagePercentage.Average 128 | $AverageMemoryUsagePercentage = [system.math]::ceiling($AverageMemoryUsagePercentage) # Round up 129 | return $AverageMemoryUsagePercentage 130 | } 131 | 132 | Function GetDatastoreCurrentDiskSpaceUsagePercentage ($DatastoreTemp) { 133 | 134 | $DatastoreFreeSpaceinMB = $DatastoreTemp.FreeSpaceMB -as [int] 135 | $DatastoreCapacityinMB= $DatastoreTemp.CapacityMB -as [int] 136 | $DatastoreCurrentDiskSpaceUsagePercentage = 100 - ($DatastoreFreeSpaceinMB / $DatastoreCapacityinMB *100) 137 | $DatastoreCurrentDiskSpaceUsagePercentage = [system.math]::ceiling($DatastoreCurrentDiskSpaceUsagePercentage) # Round up 138 | return $DatastoreCurrentDiskSpaceUsagePercentage 139 | } 140 | 141 | 142 | Function GetDatastoreCapacityinGB ($DatastoreTemp) { 143 | 144 | $DatastoreCapacityinGB = $DatastoreTemp.CapacityMB -as [int] 145 | $DatastoreCapacityinGB = $DatastoreCapacityinGB / 1024 # Divide by 1024 to convert from MB to GB 146 | $DatastoreCapacityinGB = [system.math]::ceiling($DatastoreCapacityinGB) # Round up 147 | return $DatastoreCapacityinGB 148 | } 149 | 150 | Function GetNumberofVMsInDatastore ($DatastoreTemp) { 151 | $DatastoreTemp = $DatastoreTemp | Get-VM | Measure-Object | Select-Object Count 152 | return $DatastoreTemp.Count 153 | } 154 | 155 | Function GetDatastoreAllocationPercentage ($DatastoreTemp) { 156 | $DatastoreTemp = $DatastoreTemp | Get-View 157 | $DSAllocationTemp = [math]::round(((($DatastoreTemp.Summary.Capacity - $DatastoreTemp.Summary.FreeSpace)` 158 | + $DatastoreTemp.Summary.Uncommitted)*100)/$DatastoreTemp.Summary.Capacity,0) 159 | return $DSAllocationTemp 160 | } 161 | 162 | Function GetVMHostCurrentMemoryUsagePercentage ($vmhosttemp) { 163 | 164 | $MemoryUsageinMhz = $vmhosttemp.MemoryUsageMB -as [int] 165 | $MemoryTotalinMhz = $vmhosttemp.MemoryTotalMB -as [int] 166 | $MemoryUsagePercentage = $MemoryUsageinMhz / $MemoryTotalinMhz *100 167 | $MemoryUsagePercentage = [system.math]::ceiling($MemoryUsagePercentage) # Round up 168 | return $MemoryUsagePercentage 169 | } 170 | 171 | 172 | Function GetVMHostCurrentCPUUsagePercentage ($vmhosttemp) { 173 | 174 | $CPUUsageinMhz = $vmhosttemp.CpuUsageMhz -as [int] 175 | $CPUTotalinMhz = $vmhosttemp.CpuTotalMhz -as [int] 176 | $CPUUsagePercentage = $CPUUsageinMhz / $CPUTotalinMhz *100 177 | $CPUUsagePercentage = [system.math]::ceiling($CPUUsagePercentage) # Round up 178 | return $CPUUsagePercentage 179 | } 180 | 181 | Function GetVMAverageCPUUsage ($VMsTemp) { 182 | 183 | $AverageVMCPUUsage = Get-Stat -Entity ($VMsTemp) -MaxSamples 1 -stat cpu.usagemhz.average 184 | $AverageVMCPUUsage = $AverageVMCPUUsage | Measure-Object -Property value -Average 185 | $AverageVMCPUUsage = $AverageVMCPUUsage.Average 186 | #$AverageVMCPUUsage = $AverageVMCPUUsage / 1000 # Divide by 1000 to convert from MHz to GHz # VALUE NOT HIGH ENOUGH 187 | $AverageVMCPUUsage = [system.math]::ceiling($AverageVMCPUUsage) # Round up 188 | return $AverageVMCPUUsage 189 | } 190 | 191 | Function GetVMAverageMemoryUsage ($VMsTemp) { 192 | 193 | $TotalVMMemoryinMB = $VMsTemp | Measure-Object -Property MemoryMB -Sum # Count total RAM in MB 194 | $TotalVMMemoryinMB = $TotalVMMemoryinMB.Sum -as [int] # Convert from String to Int 195 | #$TotalVMMemoryinGB = $TotalVMMemoryinMB / 1024 # Divide by 1024 to convert from MB to GB # VALUE NOT HIGH ENOUGH 196 | $AverageVMMemoryInGB = $TotalVMMemoryinMB / $VMsTemp.Length # Divide by number of VMs 197 | $AverageVMMemoryInGB = [system.math]::ceiling($AverageVMMemoryInGB) # Round down 198 | return $AverageVMMemoryInGB 199 | } 200 | 201 | Function GetVMAverageDatastoreUsage ($VMsTemp) { 202 | 203 | $TotalVMProvisionedSpaceinGB = $VMsTemp | Measure-Object -Property ProvisionedSpaceGB -Sum # Count total RAM in MB 204 | $TotalVMProvisionedSpaceinGB = $TotalVMProvisionedSpaceinGB.Sum -as [int] # Convert from String to Int 205 | $VMAverageDatastoreUsage = $TotalVMProvisionedSpaceinGB / $VMsTemp.Length # Divide by number of VMs 206 | $VMAverageDatastoreUsage = [system.math]::ceiling($VMAverageDatastoreUsage) # Round up 207 | return $VMAverageDatastoreUsage 208 | } 209 | 210 | Function GetVMTotalMemory ($VMsTemp) { 211 | 212 | $VMTotalMemory = $VMsTemp | Measure-Object -Property MemoryMB -Sum 213 | $VMTotalMemory = $VMTotalMemory.Sum / 1024 # Divide by 1024 to convert from MB to GB 214 | $VMTotalMemory = [system.math]::ceiling($VMTotalMemory) 215 | return $VMTotalMemory 216 | } 217 | 218 | Function GetVMTotalCPUs ($VMsTemp) { 219 | 220 | $VMTotalCPUs = $VMsTemp | Measure-Object -Property NumCpu -Sum 221 | return $VMTotalCPUs.Sum 222 | } 223 | 224 | 225 | Function GetCPUSlotsAvailable ($VMHostsInClusterTemp, $ClusterVMAverageCPUUsageTemp) { 226 | 227 | $VMHostsTotalCPUMhz = $VMHostsInClusterTemp | Measure-Object -Property CpuTotalMhz -Sum 228 | $VMHostsUsedCPUMhz = $VMHostsInClusterTemp | Measure-Object -Property CpuUsageMhz -Sum 229 | $VMHostsTotalCPUMhz = $VMHostsTotalCPUMhz.Sum * 0.90 # Keep 10% available for best practice 230 | $VMHostsUsedCPUMhz = $VMHostsUsedCPUMhz.Sum 231 | $VMHostsAvailableCPUMhz = $VMHostsTotalCPUMhz - $VMHostsUsedCPUMhz 232 | $ClusterCPUSlots = $VMHostsAvailableCPUMhz / $ClusterVMAverageCPUUsageTemp # The rest divided by 1 CPU Slot 233 | $ClusterCPUSlots = [system.math]::floor($ClusterCPUSlots) # Round down 234 | return $ClusterCPUSlots 235 | } 236 | 237 | 238 | 239 | Function GetMemorySlotsAvailable ($VMHostsInClusterTemp, $ClusterVMAverageMemoryUsageTemp) { 240 | 241 | $VMHostsTotalMemoryMB = $VMHostsInClusterTemp | Measure-Object -Property MemoryTotalMB -Sum 242 | $VMHostsUsedMemoryMB = $VMHostsInClusterTemp | Measure-Object -Property MemoryUsageMB -Sum 243 | $VMHostsTotalMemoryMB = $VMHostsTotalMemoryMB.Sum * 0.90 # Keep 10% available for best practice 244 | $VMHostsUsedMemoryMB = $VMHostsUsedMemoryMB.Sum 245 | $VMHostsAvailableMemoryMB = $VMHostsTotalMemoryMB - $VMHostsUsedMemoryMB 246 | $ClusterMemorySlots = $VMHostsAvailableMemoryMB / $ClusterVMAverageMemoryUsageTemp # The rest divided by 1 Memory Slot 247 | $ClusterMemorySlots = [system.math]::floor($ClusterMemorySlots) # Round down 248 | return $ClusterMemorySlots 249 | } 250 | 251 | 252 | Function GetDatastoreSlotsAvailable ($DatastoresInClusterTemp, $ClusterVMAverageMemoryUsageTemp) { 253 | 254 | # Remove 5% of Datastore capacity for Best Practices 255 | $DatastoreCapacityTemp = $DatastoresInClusterTemp | Measure-Object -Property CapacityMB -Sum 256 | $DatastoreCapacityMinus5Percent = $DatastoreCapacity.Sum * 0.95 257 | $5PercentOfDatastoreCapacity = $DatastoreCapacity.Sum - $DatastoreCapacityMinus5Percent 258 | $DatastoreFreeSpaceMB = $DatastoreFreeSpaceMB - $5PercentOfDatastoreCapacity 259 | 260 | $DatastoreFreeSpaceMB = $DatastoresInClusterTemp | Measure-Object -Property FreeSpaceMB -Sum 261 | $DatastoreFreeSpaceMB = $DatastoreFreeSpaceMB.Sum / 1024 # Divide by 1024 to convert from MB to GB 262 | $DatastoreFreeSpaceMB = $DatastoreFreeSpaceMB - $5PercentOfDatastoreCapacity # Keep 5% available for best practice 263 | $ClusterDatastoreSlots = $DatastoreFreeSpaceMB / $ClusterVMAverageMemoryUsageTemp # Divided by 1 Memory Slot 264 | $ClusterDatastoreSlots = [system.math]::floor($ClusterDatastoreSlots) # Round down 265 | return $ClusterDatastoreSlots 266 | } 267 | 268 | Function GetVMProvisioningPotential ($CPUSLOTS, $MEMORYSLOTS, $DATASTORESLOTS) { 269 | 270 | if ($CPUSLOTS -le $MEMORYSLOTS -and $CPUSLOTS -le $DATASTORESLOTS){ return ([String]$CPUSLOTS + ". CPU is your limiting factor.")} 271 | if ($MEMORYSLOTS -le $CPUSLOTS -and $MEMORYSLOTS -le $DATASTORESLOTS){ return ([String]$MEMORYSLOTS + ". Memory is your limiting factor.")} 272 | if ($DATASTORESLOTS -le $CPUSLOTS -and $DATASTORESLOTS -le $MEMORYSLOTS){ return ([String]$DATASTORESLOTS + ". Datastore Disk Space is your limiting factor.")} 273 | 274 | } 275 | 276 | Function CreateHeader ($text) { 277 | $HeaderTemp = "
" 278 | $HeaderTemp += "

" + $text + "

" 279 | $HeaderTemp += "
" 280 | $HeaderTemp += "
" 281 | return $HeaderTemp 282 | } 283 | 284 | Function ListVCenterInventory () { 285 | $InventoryTemp = "

" 286 | $HostTemp = Get-VMHost | Select-Object -First 1 287 | $InventoryTemp += "vCenter version " + (($HostTemp | Select-Object @{N="vCenterVersion";E={$global:DefaultVIServers | where {$_.Name.ToLower() -eq ($HostTemp.ExtensionData.Client.ServiceUrl.Split('/')[2]).ToLower()} | %{"$($_.Version) Build $($_.Build)"} }}).vCenterVersion) + "
" 288 | $InventoryTemp += [String]$DC.Count + " Datacenters
" 289 | $InventoryTemp += [String]$Clusters.Count + " Clusters
" 290 | $InventoryTemp += [String]$VMHosts.Count + " ESXi Hosts with a total of " + (GetTotalCPUCyclesInGhz ($VMHosts)) + " GHz on " + ` 291 | (GetTotalNumberofCPUs ($VMHosts)) + " CPUs and " + (GetTotalMemoryInGB ($VMHosts)) + " GB of RAM
" 292 | $InventoryTemp += [String]$Datastores.Count + " Datastores with a total of " + (GetTotalDatastoreDiskSpaceinGB ($Datastores)) + " GB of disk space
" 293 | $InventoryTemp += [String]$VM.Count + " Virtual Machines
" 294 | $InventoryTemp += [String]$Templates.Count + " Templates
" 295 | $InventoryTemp += [String]$ResourcePools.Count + " Resource Pools
" 296 | $InventoryTemp += [String][system.math]::floor($VM.Count / $VMHosts.Count) + ":1" + " Consolidation ratio
" 297 | $InventoryTemp += "
" 298 | 299 | $InventoryTemp += BuildESXiSoftwareAndHardwareInfoTable ($VMHosts) 300 | 301 | $InventoryTemp += "

" 302 | return $InventoryTemp 303 | } 304 | 305 | Function BuildESXiSoftwareAndHardwareInfoTable ($VMHostsTemp) { 306 | $ESXiSoftwareAndHardwareInfoTemp = "" 307 | $ESXiSoftwareAndHardwareInfoTemp += "" 308 | $ESXiSoftwareAndHardwareInfoTemp += "" ` 309 | + "" 310 | 311 | Write-Host " " Gathering ESXi Hardware and Software Information... 312 | $ESXiSoftwareAndHardwareInfoTemp += $VMHostsTemp | Sort-Object name | ForEach-Object { 313 | "" 316 | } 317 | 318 | $ESXiSoftwareAndHardwareInfoTemp += "
ESXi Software and Hardware Information
Host NameServer ModelNumber of CPUsRAM Quantity (in GB)ESXi VersionUptime
" + $_.Name + "" + $_.Manufacturer + " " + $_.Model + "" + $_.NumCpu + " CPUs " ` 314 | + (GetTotalMemoryInGB ($_)) + " GB " + $_.Version + " Build " + $_.Build + "" ` 315 | + ($_ | Get-View | select @{N="Uptime"; E={(Get-Date) - $_.Summary.Runtime.BootTime}}).Uptime.Days + " days

" 319 | 320 | return $ESXiSoftwareAndHardwareInfoTemp 321 | } 322 | 323 | 324 | 325 | 326 | Function ListClusterInventory ($ClusterTemp) { 327 | 328 | Write-Host " " Gathering $ClusterTemp.Name "inventory..." 329 | 330 | # Get inventory objects for this cluster only 331 | $VMHostsTemp = Get-Cluster $ClusterTemp.Name | Get-VMHost | Sort-Object -Property Name #| Select-Object -First 1 332 | $DatastoresTemp = Get-Cluster $ClusterTemp.Name | Get-VMHost | Get-Datastore | Sort-Object -Property Name #| Select-Object -First 1 333 | $VMTemp = Get-Cluster $ClusterTemp.Name | Get-VM | Sort-Object -Property Name #| Select-Object -First 1 334 | $ResourcePoolsTemp = Get-Cluster $ClusterTemp.Name | Get-ResourcePool | Sort-Object -Property Name #| Select-Object -First 1 335 | 336 | 337 | $InventoryTemp = "

" 338 | $InventoryTemp += [String]$VMHostsTemp.Count + " ESXi Hosts with a total of " + (GetTotalCPUCyclesInGhz ($VMHostsTemp)) + " GHz on " + ` 339 | (GetTotalNumberofCPUs ($VMHostsTemp)) + " CPUs and " + (GetTotalMemoryInGB ($VMHostsTemp)) + " GB of RAM
" 340 | $InventoryTemp += [String]$DatastoresTemp.Count + " Datastores with a total of " + (GetTotalDatastoreDiskSpaceinGB ($DatastoresTemp)) + " GB of disk space
" 341 | $InventoryTemp += [String]$VMTemp.Count + " Virtual Machines
" 342 | $NbOfResourcePoolsTemp = $ResourcePoolsTemp | Measure-Object; 343 | $InventoryTemp += [String]$NbOfResourcePoolsTemp.Count + " Resource Pools
" 344 | $InventoryTemp += [String][system.math]::floor($VMTemp.Count / $VMHostsTemp.Count) + ":1" + " Consolidation ratio
" 345 | $InventoryTemp += "
" 346 | $InventoryTemp += BuildESXiSoftwareAndHardwareInfoTable ($VMHostsTemp) 347 | 348 | $InventoryTemp += "

" 349 | return $InventoryTemp 350 | } 351 | 352 | Function ReinitializeArrays (){ #Reinitialize variables for reuse 353 | Clear-Variable -Name ArrayOfNames 354 | Clear-Variable -Name ArrayOfValues 355 | $global:ArrayOfNames = @() 356 | $global:ArrayOfValues = @() 357 | } 358 | 359 | Function CreateVMHostCPUUsageTable ($VMHostsTemp){ # Builds CPU HTML Table and populates Arrays used to create chart 360 | 361 | $CPUTableTemp = "" 362 | $CPUTableTemp += "" 363 | $CPUTableTemp += "" ` 364 | + "" 365 | 366 | $CPUTableTemp += $VMHostsTemp | Sort-Object name | ForEach-Object { 367 | Write-Host " " Gathering $_.Name "CPU usage statistics..." 368 | $tempVMHostAverageCPUUsagePercentage = (GetVMHostAverageCPUUsagePercentage $_) 369 | "" 371 | $global:ArrayOfNames += $_.Name 372 | $global:ArrayOfValues += ($tempVMHostAverageCPUUSagePercentage) 373 | } 374 | 375 | $CPUTableTemp += "
ESXi Host CPU Usage Statistics
Host NameNumber of CPUsCurrent CPU Usage %Monthly Average CPU Usage %
" + $_.name + " " + $_.NumCpu + " CPUs " + (GetVMHostCurrentCPUUsagePercentage $_) ` 370 | + "% " + ($tempVMHostAverageCPUUSagePercentage) + "%
" 376 | return $CPUTableTemp 377 | } 378 | 379 | Function CreateVMHostMemoryUsageTable ($VMHostsTemp){ # Builds Memory HTML Table and populates Arrays used to create chart 380 | $MemoryTableTemp = "" 381 | $MemoryTableTemp += "" 382 | $MemoryTableTemp += "" 384 | 385 | 386 | 387 | $MemoryTableTemp += $VMHostsTemp | Sort-Object name | ForEach-Object { 388 | Write-Host " " Gathering $_.Name "Memory usage statistics..." 389 | $tempVMHostAverageMemoryUsagePercentage = (GetVMHostAverageMemoryUsagePercentage $_) 390 | "" 392 | $global:ArrayOfNames += $_.Name 393 | $global:ArrayOfValues += ($tempVMHostAverageMemoryUsagePercentage) 394 | } 395 | 396 | 397 | $MemoryTableTemp += "
ESXi Host Memory Usage Statistics
Host NameRAM Quantity (in GB)Current Memory Usage % " ` 383 | + "Monthly Average Memory Usage %
" + $_.name + " " + (GetVMHostMemoryinGB $_) + " GB " + (GetVMHostCurrentMemoryUsagePercentage $_) ` 391 | + "% " + ($tempVMHostAverageMemoryUsagePercentage) + "%
" 398 | return $MemoryTableTemp 399 | } 400 | 401 | Function CreateDatastoreUsageTable ($DatastoresTemp){ # Builds Datastore HTML Table and populates Arrays used to create chart 402 | 403 | $DatastoreTableTemp += "" 404 | $DatastoreTableTemp += "" 405 | $DatastoreTableTemp += "" ` 406 | + "" 407 | 408 | 409 | $DatastoreTableTemp += $DatastoresTemp | Sort-Object name | ForEach-Object { 410 | Write-Host " " Gathering $_.Name "Datastore usage statistics..." 411 | "" ` 413 | + "" 414 | 415 | $global:ArrayOfNames += $_.Name 416 | $global:ArrayOfValues += (GetDatastoreCurrentDiskSpaceUsagePercentage $_) 417 | } 418 | 419 | 420 | $DatastoreTableTemp += "
Datastore Usage Statistics
Datastore NameTotal Disk Space (in GB)Current Usage % Number of VMs containedCommitment %
" + $_.name + " " + (GetDatastoreCapacityinGB $_) + " GB " + ` 412 | (GetDatastoreCurrentDiskSpaceUsagePercentage $_) + "% " + (GetNumberofVMsInDatastore $_)+ "" + (GetDatastoreAllocationPercentage $_) + "%
" 421 | return $DatastoreTableTemp 422 | } 423 | 424 | Function CreateClusterProvisioningPotentialTables ($ClusterTemp) { 425 | 426 | 427 | $VMsInClusterTemp = $ClusterTemp | Get-VM 428 | 429 | # Remove biggest host from collection 430 | $BiggestHostInCluster = $ClusterTemp | Get-VMHost | Sort-Object MemoryTotalMB -Descending | Select-Object -First 1 431 | $VMHostsInClusterMinusBiggest = $ClusterTemp | Get-VMHost | Where-Object {$_.Name -ne $BiggestHostInCluster.Name} 432 | $DatastoresInClusterMinusBiggestHosts = $VMHostsInClusterMinusBiggest | Get-Datastore 433 | 434 | $ClusterVMAverageCPUUsage = (GetVMAverageCPUUsage ($VMsInClusterTemp)) 435 | $ClusterVMAverageMemoryUsage = (GetVMAverageMemoryUsage ($VMsInClusterTemp)) 436 | $ClusterVMAverageDatastoreUsage = (GetVMAverageDatastoreUsage ($VMsInClusterTemp)) 437 | 438 | $AvailableCPUSlotsInCluster = (GetCPUSlotsAvailable $VMHostsInClusterMinusBiggest $ClusterVMAverageCPUUsage) 439 | $AvailableMemorySlotsInCluster = (GetMemorySlotsAvailable $VMHostsInClusterMinusBiggest $ClusterVMAverageMemoryUsage) 440 | $AvailableDatastoreSlotsInCluster = (GetDatastoreSlotsAvailable $DatastoresInClusterMinusBiggestHosts $ClusterVMAverageDatastoreUsage) 441 | 442 | # Average Usage Statistics Table 443 | $ClusterProvisioningTableTemp += "" 444 | $ClusterProvisioningTableTemp += "" 445 | $ClusterProvisioningTableTemp += "" 446 | $ClusterProvisioningTableTemp += "" 448 | $ClusterProvisioningTableTemp += "
Virtual Machine Average Usage Statistics
Total Number of VMsAverage VM CPU UsageAverage VM Memory UsageAverage VM Datastore Usage
" + $VMsInCluster.Length + "" + $ClusterVMAverageCPUUsage + " MHz " + $ClusterVMAverageMemoryUsage + " MB " + ` 447 | $ClusterVMAverageDatastoreUsage + " GB
" 449 | 450 | $ClusterProvisioningTableTemp += "
" 451 | 452 | # Available Resource Slots Table 453 | $ClusterProvisioningTableTemp += "" 454 | $ClusterProvisioningTableTemp += "" 455 | $ClusterProvisioningTableTemp += "" 456 | $ClusterProvisioningTableTemp += "" 458 | $ClusterProvisioningTableTemp += "
Available Virtual Machine Resource Slots
1 Slot = Average VM allocationCPU Slots AvailableMemory Slots AvailableDatastore Slots Available
" + $AvailableCPUSlotsInCluster + "" + $AvailableMemorySlotsInCluster ` 457 | + "" + $AvailableDatastoreSlotsInCluster + "
" 459 | 460 | $ClusterProvisioningTableTemp += "
" 461 | 462 | # Provisioning potential Table 463 | $ClusterProvisioningTableTemp += "" 464 | $ClusterProvisioningTableTemp += "" 465 | $ClusterProvisioningTableTemp += "" 467 | 468 | $ClusterProvisioningTableTemp += "" 469 | $ClusterProvisioningTableTemp += "
Virtual Machine Provisioning Potential
The approximate number of Virtual Machines you can provision safely in this cluster is " + ` 466 | (GetVMProvisioningPotential $AvailableCPUSlotsInCluster $AvailableMemorySlotsInCluster $AvailableDatastoreSlotsInCluster) + "*
*Calculations are according to CPU, Memory and Datastore disk space VM average statistics. Statistics are calculated conservatively.

" 470 | 471 | return $ClusterProvisioningTableTemp 472 | 473 | } 474 | 475 | Function CreateClusterResilienceTable ($ClusterTemp) { 476 | 477 | Write-Host " " Gathering Cluster Resilience Information for Cluster $ClusterTemp.Name 478 | 479 | # Get HA info 480 | $HAEnabled = $ClusterTemp | Select-Object HAEnabled; $HAEnabled = $HAEnabled.HAEnabled 481 | $ACEnabled = $ClusterTemp | Select-Object HAAdmissionControlEnabled; $ACEnabled = $ACEnabled.HAAdmissionControlEnabled 482 | $ACPolicy = "N/A" 483 | $HostLossTolerance = 0 484 | 485 | # GET HA Admission Control Policy 486 | if ($HAEnabled -and $ACEnabled){ 487 | 488 | if ((($ClusterTemp | Select-Object HAFailoverlevel).HAFailoverLevel) -eq 0){ # If protection setting is NOT a # of hosts 489 | 490 | $ClusterView = Get-View -ViewType "ClusterComputeResource" -Filter @{"Name" = $ClusterTemp.Name} 491 | $ACPolicyInteger = $ClusterView.configuration.dasConfig.admissionControlpolicy.cpuFailoverResourcesPercent 492 | $ACPolicy = [String]$ACPolicyInteger + " % of resources reserved" 493 | 494 | 495 | # CHART VALUE PREPARATIONS 496 | $ClusterUsedMemory = ($ClusterTemp | Get-VMHost | Measure-Object MemoryUsageMB -Sum).sum 497 | $ClusterTotalMemory = ($ClusterTemp | Get-VMHost | Measure-Object MemoryTotalMB -Sum).sum 498 | $ClusterFreeMemory = $ClusterTotalMemory - $ClusterUsedMemory - $ACPolicyInteger 499 | $ClusterUsedMemoryPercentage = [system.math]::floor($ClusterUsedMemory * 100 / $ClusterTotalMemory) 500 | $ClusterFreeMemoryPercentage = [system.math]::floor($ClusterFreeMemory * 100 / $ClusterTotalMemory) 501 | $ClusterFreeMemoryPercentage = $ClusterFreeMemoryPercentage - $ACPolicyInteger 502 | 503 | $global:ArrayOfNames += "Used" 504 | $global:ArrayOfValues += $ClusterUsedMemoryPercentage 505 | 506 | $global:ArrayOfNames += "Free" 507 | $global:ArrayOfValues += $ClusterFreeMemoryPercentage 508 | 509 | $global:ArrayOfNames += "HA Admission Control Reservation" 510 | $global:ArrayOfValues += $ACPolicyInteger 511 | 512 | # Host Loss Tolerance Calculation 513 | $BiggestHostInCluster = $ClusterTemp | Get-VMHost | Sort-Object MemoryTotalMB -Descending | Select-Object -First 1 514 | $HAReservedMemory = ($ACPolicyInteger/100) * ($ClusterTemp | Get-VMHost | Measure-Object MemoryTotalMB -Sum).sum 515 | $HostLossTolerance = $HAReservedMemory / $BiggestHostInCluster.MemoryTotalMB 516 | $HostLossTolerance = [System.Math]::Round($HostLossTolerance,2) 517 | 518 | 519 | }else{ # If protection setting is a # of hosts 520 | 521 | $ACPolicy = ($ClusterTemp | Select-Object HAFailoverlevel).HAFailoverLevel 522 | $ACPolicy = [String]$ACPolicy + " host(s) reserved" 523 | $HostLossTolerance = ($ClusterTemp | Select-Object HAFailoverlevel).HAFailoverLevel 524 | } 525 | } 526 | 527 | # Build HTML Table 528 | $ClusterResilienceTableTemp += "" 529 | $ClusterResilienceTableTemp += "" 530 | $ClusterResilienceTableTemp += "" 531 | $ClusterResilienceTableTemp += "" 532 | $ClusterResilienceTableTemp += "" 533 | $ClusterResilienceTableTemp += "
Cluster Resilience Report
HA EnabledAdmission Control EnabledAdmission Control Policy
" + $HAEnabled + " " + $ACEnabled + " " + $ACPolicy + "
This cluster can survive the loss of approximately " + $HostLossTolerance + " host(s)

" 534 | 535 | return $ClusterResilienceTableTemp 536 | 537 | 538 | } 539 | 540 | Function CreateVirtualMachineOSTable ($VMsTemp){ # Builds VM HTML Table and populates Arrays used to create chart 541 | 542 | Write-Host " " Collecting Virtual Machine Guest OS information... 543 | 544 | # Calculate how many of each Guest OS 545 | $NumberOfWindowsVMs = $VMsTemp | Where-Object {$_.Guest -like "*Windows*"} | Measure-Object 546 | $NumberOfWindowsVMs = $NumberOfWindowsVMs.Count 547 | $NumberOfLinuxVMs = $VMsTemp | Where-Object {$_.Guest -like "*inux*" -OR $_.Guest -like "*nix*"} | Measure-Object 548 | $NumberOfLinuxVMs = $NumberOfLinuxVMs.Count 549 | $NumberOfOtherVMs = [int]$VMsTemp.Length - ([int]$NumberOfWindowsVMs + [int]$NumberOfLinuxVMs) 550 | 551 | # Build HTML Table 552 | $VMTableTemp += "" 553 | $VMTableTemp += "" 554 | $VMTableTemp += "" 555 | $VMTableTemp += "" 556 | $VMTableTemp += "" 557 | $VMTableTemp += "" 558 | $VMTableTemp += "" 559 | $VMTableTemp += "
Virtual Machine Guest OS Breakdown
Operating System TypeNumber of VMs
Windows " + $NumberOfWindowsVMs + "
Linux/Unix " + $NumberOfLinuxVMs + "
Other " + $NumberOfOtherVMs + "
TOTAL " + $VMsTemp.Length + "

" 560 | 561 | # Populate Arrays to create Chart 562 | $global:ArrayOfNames += "Windows" 563 | $global:ArrayOfNames += "Linux/Unix" 564 | $global:ArrayOfNames += "Other" 565 | $global:ArrayOfValues += $NumberOfWindowsVMs 566 | $global:ArrayOfValues += $NumberOfLinuxVMs 567 | $global:ArrayOfValues += $NumberOfOtherVMs 568 | 569 | return $VMTableTemp 570 | } 571 | 572 | # Credit to Sean from Shogun Tech : 573 | #http://www.shogan.co.uk/vmware/generating-graphical-charts-with-vmware-powercli-powershell/ 574 | Function Create-Chart() { 575 | 576 | Param( 577 | [String]$ChartType, 578 | [String]$ChartTitle, 579 | [String]$FileName, 580 | [String]$XAxisName, 581 | [String]$YAxisName, 582 | [Int]$ChartWidth, 583 | [Int]$ChartHeight, 584 | [String[]]$NameArray, #Added by MVD 585 | [Int[]]$ValueArray #Added by MVD 586 | ) 587 | 588 | [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 589 | [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") 590 | 591 | Write-Host " " Creating chart... 592 | 593 | #Create our chart object 594 | $Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart 595 | $Chart.Width = $ChartWidth 596 | $Chart.Height = $ChartHeight 597 | $Chart.Left = 10 598 | $Chart.Top = 10 599 | 600 | #Create a chartarea to draw on and add this to the chart 601 | $ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea 602 | $Chart.ChartAreas.Add($ChartArea) 603 | [void]$Chart.Series.Add("Data") 604 | 605 | $Chart.ChartAreas[0].AxisX.Interval = "1" #Set this to 1 (default is auto) and allows all X Axis values to display correctly 606 | $Chart.ChartAreas[0].AxisX.IsLabelAutoFit = $false; 607 | $Chart.ChartAreas[0].AxisX.LabelStyle.Angle = "-45" 608 | 609 | #Add the Actual Data to our Chart 610 | $Chart.Series["Data"].Points.DataBindXY($NameArray, $ValueArray) #Modified by MVD 611 | 612 | if (($ChartType -eq "Pie") -or ($ChartType -eq "pie")) { 613 | $ChartArea.AxisX.Title = $XAxisName 614 | $ChartArea.AxisY.Title = $YAxisName 615 | $Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie 616 | $Chart.Series["Data"]["PieLabelStyle"] = "Outside" 617 | $Chart.Series["Data"]["PieLineColor"] = "Black" 618 | $Chart.Series["Data"]["PieDrawingStyle"] = "Concave" 619 | #($Chart.Series["Data"].Points.FindMaxByValue())["Exploded"] = $true 620 | $Chart.Series["Data"].Label = "#VALX = #VALY\n" # Give an X & Y Label to the data in the plot area (useful for Pie graph) 621 | #(Display both axis labels, use: Y = #VALY\nX = #VALX) 622 | } 623 | 624 | elseif (($ChartType -eq "Bar") -or ($ChartType -eq "bar")) { 625 | #$Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Descending, "Y") 626 | $ChartArea.AxisX.Title = $XAxisName 627 | $ChartArea.AxisY.Title = $YAxisName 628 | # Find point with max/min values and change their colour 629 | $maxValuePoint = $Chart.Series["Data"].Points.FindMaxByValue() 630 | $maxValuePoint.Color = [System.Drawing.Color]::Red 631 | $minValuePoint = $Chart.Series["Data"].Points.FindMinByValue() 632 | $minValuePoint.Color = [System.Drawing.Color]::Green 633 | # make bars into 3d cylinders 634 | $Chart.Series["Data"]["DrawingStyle"] = "Cylinder" 635 | $Chart.Series["Data"].Label = "#VALY" # Give a Y Label to the data in the plot area (useful for Bar graph) 636 | } 637 | 638 | else { 639 | Write-Host "No Chart Type was defined. Try again and enter either Pie or Bar for the ChartType Parameter. " ` 640 | "The chart will be created as a standard Bar Graph Chart for now." -ForegroundColor Cyan 641 | } 642 | 643 | #Set the title of the Chart to the current date and time 644 | $Title = new-object System.Windows.Forms.DataVisualization.Charting.Title 645 | $Chart.Titles.Add($Title) 646 | $Chart.Titles[0].Text = $ChartTitle 647 | 648 | #Save the chart to a file 649 | $FullPath = ((Get-Location).Path + "\" + $FileName + ".png") 650 | $Chart.SaveImage($FullPath,"png") 651 | #Write-Host "Chart saved to $FullPath" -ForegroundColor Green 652 | 653 | #return $FullPath 654 | 655 | } 656 | 657 | ################################################# OUTPUT ########################################################## 658 | 659 | ######################## INVENTORY ############################ 660 | 661 | Write-Host Step 1/6 - Collecting inventory... 662 | 663 | $HTMLBody = "" 664 | $HTMLBody += "$Date
" 665 | $HTMLBody += "

VMWare Capacity & Performance Report for " + $vCenterServerName + "

" 666 | 667 | $HTMLBody += CreateHeader ("INVENTORY FOR vCENTER " + $vCenterServerName + "") 668 | $HTMLBody += ListVCenterInventory 669 | $HTMLBody += 670 | 671 | 672 | ######################## vCenter CPU CAPACITY REPORT ############################ 673 | 674 | Write-Host Step 2/6 - Collecting CPU statistics... 675 | 676 | # HEADER 677 | $HTMLBody += CreateHeader ("CPU CAPACITY REPORT FOR vCENTER " + $vCenterServerName + "") 678 | 679 | # INTRO TEXT 680 | $HTMLBody += "" + [String]$VMHosts.Count + " ESXi Hosts with a total of " + (GetTotalCPUCyclesInGhz ($VMHosts)) + " GHz on " + 681 | (GetTotalNumberofCPUs ($VMHosts)) + " CPUs

" 682 | 683 | # TABLE 684 | $HTMLBody += CreateVMHostCPUUsageTable ($VMHosts) 685 | 686 | # CHART 687 | Create-Chart -ChartType Bar -ChartTitle "Monthly Average Host CPU Usage Percentage" -FileName ("vCenter_CPU_Usage") -ChartWidth 750 ` 688 | -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 689 | $HTMLBody += "" 690 | $Attachments += "vCenter_CPU_Usage.png" 691 | 692 | # CLEANUP 693 | ReinitializeArrays 694 | 695 | 696 | ######################## vCenter MEMORY CAPACITY REPORT ############################ 697 | 698 | Write-Host Step 3/6 - Collecting Memory information... 699 | # HEADER 700 | $HTMLBody += CreateHeader ("MEMORY CAPACITY REPORT FOR vCENTER " + $vCenterServerName + "") 701 | 702 | # INTRO TEXT 703 | $HTMLBody += "" + [String]$VMHosts.Count + " ESXi Hosts with a total of " + (GetTotalMemoryInGB ($VMHosts)) + " GB of RAM

" 704 | 705 | # TABLE 706 | $HTMLBody += CreateVMHostMemoryUsageTable ($VMHosts) 707 | 708 | # CHART 709 | Create-Chart -ChartType Bar -ChartTitle "Monthly Average Host Memory Usage Percentage" -FileName ("vCenter_Memory_Usage") -ChartWidth 750 ` 710 | -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 711 | $HTMLBody += "" 712 | $Attachments += "vCenter_Memory_Usage.png" 713 | 714 | # CLEANUP 715 | ReinitializeArrays 716 | 717 | 718 | ######################## vCenter DATASTORE CAPACITY REPORT ############################ 719 | 720 | Write-Host Step 4/6 - Collecting Datastore information... 721 | 722 | # HEADER 723 | $HTMLBody += CreateHeader ("DATASTORE CAPACITY REPORT FOR vCENTER " + $vCenterServerName + "") 724 | 725 | # INTRO TEXT 726 | $HTMLBody += "" + [String]$Datastores.Count + " Datastores with a total of " + (GetTotalDatastoreDiskSpaceinGB ($Datastores)) + ` 727 | " GB of disk space

" 728 | 729 | # TABLE 730 | $HTMLBody += CreateDatastoreUsageTable ($Datastores) 731 | 732 | # CHART 733 | Create-Chart -ChartType Bar -ChartTitle "Datastore Usage Percentage " -FileName ("vCenter_Datastore_Usage") -ChartWidth 1200 ` 734 | -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 735 | $HTMLBody += "" 736 | $Attachments += "vCenter_Datastore_Usage.png" 737 | 738 | # CLEANUP 739 | ReinitializeArrays 740 | 741 | 742 | ######################## vCenter VIRTUAL MACHINE REPORT ############################ 743 | 744 | Write-Host Step 5/6 - Collecting Virtual Machine information... 745 | 746 | # HEADER 747 | $HTMLBody += CreateHeader ("VIRTUAL MACHINE REPORT FOR vCENTER " + $vCenterServerName + "") 748 | 749 | # INTRO TEXT 750 | $HTMLBody += "" + [String]$VM.Count + " Virtual Machines

" 751 | 752 | # TABLE 753 | $HTMLBody += CreateVirtualMachineOSTable ($VM) 754 | 755 | # CHART 756 | Create-Chart -ChartType Pie -ChartTitle "VM Operating System Report" -FileName ("vCenter_VM_OS_Report") -ChartWidth 750 ` 757 | -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 758 | $HTMLBody += "" 759 | $Attachments += "vCenter_VM_OS_Report.png" 760 | 761 | # CLEANUP 762 | ReinitializeArrays 763 | 764 | 765 | 766 | ######################## PER CLUSTER REPORT ############################ 767 | 768 | Write-Host Step 6/6 - Collecting Cluster information... 769 | 770 | # Loop through all clusters 771 | ForEach ($ClusterTemp in ($Clusters)){ 772 | 773 | $NumberOfVMHostsInCluster = $ClusterTemp | Get-VMHost | Measure-Object 774 | $NumberOfVMHostsInCluster = $NumberOfVMHostsInCluster.Count 775 | 776 | If ($NumberOfVMHostsInCluster -gt 1){ #Ignore Clusters with no ESXi hosts in it 777 | 778 | Write-Host " " Gathering $ClusterTemp.Name "usage statistics..." 779 | 780 | 781 | $VMHostsInCluster = $ClusterTemp | Get-VMHost 782 | $DatastoresInCluster = $ClusterTemp | Get-VMHost | Get-Datastore 783 | $VMsInCluster = $ClusterTemp | Get-VM 784 | 785 | ################################# PER CLUSTER INVENTORY ########################## 786 | 787 | # HEADER 788 | $HTMLBody += CreateHeader ("INVENTORY FOR CLUSTER " + $ClusterTemp.Name + "") 789 | 790 | # INVENTORY 791 | $HTMLBody += ListClusterInventory ($ClusterTemp) 792 | 793 | ################################# PER CLUSTER CPU REPORT ########################## 794 | # HEADER 795 | $HTMLBody += CreateHeader ("CPU CAPACITY REPORT FOR CLUSTER " + $ClusterTemp.Name + "") 796 | 797 | # INTRO TEXT 798 | $HTMLBody += "" + [String]$VMHostsInCluster.Count + " ESXi Hosts with a total of " + (GetTotalCPUCyclesInGhz ($VMHostsInCluster)) + " GHz on " + 799 | (GetTotalNumberofCPUs ($VMHostsInCluster)) + " CPUs

" 800 | 801 | # TABLE 802 | $HTMLBody += CreateVMHostCPUUsageTable ($VMHostsInCluster) 803 | 804 | # CHART 805 | Create-Chart -ChartType Bar -ChartTitle "Monthly Average Host CPU Usage Percentage" -FileName ("Cluster_" + ` 806 | ($ClusterTemp.Name -replace " ", "-") + "_CPU_Usage") -ChartWidth 750 -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 807 | $HTMLBody += "" 808 | $Attachments += "Cluster_" + ($ClusterTemp.Name -replace " ", "-") + "_CPU_Usage.png" 809 | 810 | # CLEANUP 811 | ReinitializeArrays 812 | 813 | ################################# PER CLUSTER MEMORY REPORT ########################## 814 | 815 | # HEADER 816 | $HTMLBody += CreateHeader ("MEMORY CAPACITY REPORT FOR CLUSTER " + $ClusterTemp.Name + "") 817 | 818 | # INTRO TEXT 819 | $HTMLBody += "" + [String]$VMHostsInCluster.Count + " ESXi Hosts with a total of " + (GetTotalMemoryInGB ($VMHostsInCluster)) + " GB of RAM

" 820 | 821 | # TABLE 822 | $HTMLBody += CreateVMHostMemoryUsageTable ($VMHostsInCluster) 823 | 824 | # CHART 825 | Create-Chart -ChartType Bar -ChartTitle "Monthly Average Host Memory Usage Percentage" -FileName ("Cluster_" + ` 826 | ($ClusterTemp.Name -replace " ", "-") + "_Memory_Usage") -ChartWidth 750 -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 827 | $HTMLBody += "" 828 | $Attachments += "Cluster_" + ($ClusterTemp.Name -replace " ", "-") + "_Memory_Usage.png" 829 | 830 | # CLEANUP 831 | ReinitializeArrays 832 | 833 | ################################# PER CLUSTER DATASTORE REPORT ########################## 834 | 835 | # HEADER 836 | $HTMLBody += CreateHeader ("DATASTORE CAPACITY REPORT FOR CLUSTER " + $ClusterTemp.Name + "") 837 | 838 | # INTRO TEXT 839 | $HTMLBody += "" + [String]$DatastoresInCluster.Count + " Datastores with a total of " + (GetTotalDatastoreDiskSpaceinGB ($DatastoresInCluster)) + ` 840 | " GB of disk space

" 841 | 842 | # TABLE 843 | $HTMLBody += CreateDatastoreUsageTable ($DatastoresInCluster) 844 | 845 | # CHART 846 | Create-Chart -ChartType Bar -ChartTitle "Datastore Usage Percentage " -FileName ("Cluster_" + ($ClusterTemp.Name -replace " ", "-") + ` 847 | "_Datastore_Usage") -ChartWidth 850 -ChartHeight 650 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 848 | $HTMLBody += "" 849 | $Attachments += "Cluster_" + ($ClusterTemp.Name -replace " ", "-") + "_Datastore_Usage.png" 850 | 851 | # CLEANUP 852 | ReinitializeArrays 853 | 854 | 855 | ################################# PER CLUSTER PROVISONING POTENTIAL REPORT ########################## 856 | 857 | 858 | # HEADER 859 | $HTMLBody += CreateHeader ("PROVISIONING POTENTIAL REPORT FOR CLUSTER " + $ClusterTemp.Name + "") 860 | 861 | # INTRO TEXT 862 | $HTMLBody += "" + [String]$VMsInCluster.Length + " Virtual Machines with a total of " + (GetVMTotalCPUs ($VMsInCluster)) + " vCPUs and " + ` 863 | (GetVMTotalMemory ($VMsInCluster)) + " GB of vRAM

" 864 | 865 | Write-Host " " Calculating Virtual Machine Average Usage Statistics for Cluster $ClusterTemp.Name 866 | 867 | # TABLE 868 | $HTMLBody += CreateClusterProvisioningPotentialTables ($ClusterTemp) 869 | 870 | 871 | 872 | ################################# PER CLUSTER RESILIENCE REPORT ########################## 873 | 874 | # HEADER 875 | $HTMLBody += CreateHeader ("CLUSTER RESILIENCE REPORT FOR CLUSTER " + $ClusterTemp.Name + "") 876 | 877 | # INTRO TEXT 878 | $HTMLBody += "" + [String]$VMHostsInCluster.Count + " ESXi Hosts with a total of " + (GetTotalCPUCyclesInGhz ($VMHostsInCluster)) + " GHz on " + 879 | (GetTotalNumberofCPUs ($VMHostsInCluster)) + " CPUs and " + (GetTotalMemoryInGB ($VMHostsInCluster)) + " GB of RAM
" 880 | $HTMLBody += "" + [String]$DatastoresInCluster.Count + " Datastores with a total of " + (GetTotalDatastoreDiskSpaceinGB ($DatastoresInCluster)) + ` 881 | " GB of disk space

" 882 | 883 | #TABLE 884 | $HTMLBody += CreateClusterResilienceTable ($ClusterTemp) 885 | 886 | 887 | # CHART 888 | if ($global:ArrayOfNames.count -gt 0){ # If HA Admission Control is set to a %, create a pie chart 889 | Create-Chart -ChartType Pie -ChartTitle "Cluster Resilience Report" -FileName ("Cluster_" + ($ClusterTemp.Name -replace " ", "-") + ` 890 | "_Resilience_Report") -ChartWidth 850 -ChartHeight 750 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues 891 | $HTMLBody += "" 892 | $Attachments += "Cluster_" + ($ClusterTemp.Name -replace " ", "-") + "_Resilience_Report.png" 893 | } 894 | 895 | # CLEANUP 896 | ReinitializeArrays 897 | 898 | #----------------------------------------------------------------------------------------------- 899 | # Change the color of the Header for the next Cluster 900 | $ColorArrayIndex++ 901 | 902 | } 903 | } 904 | 905 | 906 | 907 | ########################### SEND REPORT BY E-MAIL ################################# 908 | $HTMLBody += "" # Close HTML Body 909 | $HTMLPage = $HTMLHeader + $HTMLBody + $HTMLFooter 910 | $HTMLPage | Out-File ((Get-Location).Path + "\report.html") # Export locally to html file 911 | Write-Host "Report has exported to HTML file " + ((Get-Location).Path + "\report.html") 912 | Send-Mailmessage -From $FromAddress -To $ToAddress -Subject $Subject -Attachments $Attachments -BodyAsHTML -Body $HTMLPage -Priority Normal -SmtpServer $SMTPServer -UseSSL -Credential (Get-Credential) 913 | Write-Host "Report has been sent by E-mail to " $ToAddress " from " $FromAddress 914 | 915 | Exit --------------------------------------------------------------------------------