Jan 282015
 

After reviewing this Blog and KBs from VMware, it appears that security wins again.   VMware plans to disable Transparent Page Sharing (TPS) in all future releases.
http://kb.vmware.com/kb/2080735
http://kb.vmware.com/kb/2097593
blogs.vmware.com/vsphere/2015/01/assess-the-performance-impact-of-the-security-change-in-transparent-page-sharing-behaviour.html
*The above blog has a great GUI if you like GUIs.  Below I will post some simple Powershell code if you like exporting to Excel etc.  Quick note to Mark: Thank you for the script idea!  Check out my Plink command below so you can reduce your SSH sessions in half.  I also made some powershell commands so we don’t need to export and import text files.  This script was able to scan over 500 ESXi hosts across seven vcenters in under seven minutes.

What this script does:
1 – Pulls all hosts in your vcenter and collects the name, clusterMoRef, and if its in lock down mode
2 – Pulls all clusters in your vcenter and collects the name, MoRef, and total memory allocated in the cluster.
3 - It then uses Plink.exe to SSH into every ESX host (that is not in lockdown mode) and run two commands.
4 – It returns those commands into a fancy report that can be exported to CSV.

From there, you can make some fancy calculations between total cluster memory and TPS savings.  What I did was group all hosts by cluster, add up all of the “Free memory” reported by each host, then check if that number was smaller than the amount saved from TPS.
Thus :  if (Free Mem < TPS saved) then {bad news}

 

#####################################
#edit the following four vars – then paste the code below it
###### The Vars:
cd e:\plink
$PuttyUser = “root”
$PuttyPwd = “salsa”
$avcenter = “MyvCenter”

#####  The Code:
$Plink = “./plink.exe”
$cmd1 = ‘vsish -e get /memory/comprehensive‘
$cmd2 = ‘vsish -e get /memory/pshare/stats‘
$RCommand = ‘”‘ + $cmd1 + ‘ & ‘+ $cmd2 + ‘”‘
$report = @()
$clusterReport = @()
Add-PSSnapin VMware.*
connect-viserver $avcenter -User “administrator@vsphere.local” -password “salsa”
$hostlist = get-view -viewtype hostsystem -property name,Parent,config | select name,parent -expandproperty config | where {$_.admindisabled -ne $true} | select name,parent
$allclusters = get-view -viewtype ClusterComputeResource -property name,summary | select name,moref -expandproperty summary | select name,moref,totalmemory
$clusterReport += $allclusters
foreach($hostname in $hostlist.name){
echo Y | ./plink.exe -l $PuttyUser -pw $PuttyPwd $hostname exit
$command = $Plink + ” -v -batch -pw ” + “`””+$PuttyPwd + ”`” -l ” + $PuttyUser + “ ” + $hostname + ” ” + $RCommand
$data1 = “”
$data1 = Invoke-Expression -command $command
$VMKernelMem = ((($data1 | where {$_ -match “Given to VMKernel”}).split(‘:’)[1]) -replace ‘kb’) / 1048576
$FreeMem = ((($data1 | where {$_ -match “Free:”}).split(‘:’)[1]) -replace ‘kb’) / 1048576
$Pageshared = ($data1 | where {$_ -match “psharing”}).split(‘:’)[1]
$PageZero = ($data1 | where {$_ -match “zero-pages”}).split(‘:’)[1]
if($pageshared -gt 0){$Pageshared=[math]::Round((([int]$Pageshared*4)/1048576),2)}
if($pageZero -gt 0){$pageZero=[math]::Round((([int]$Pagezero*4)/1048576),2)}
$row = “” | select vcenter,cluster,hostname,VMKernelMemGB,FreeMemGB,PagesharedGB,PageZeroGB
$row.vcenter = $avcenter
$row.cluster = ($allclusters | where {$_.moref.value -match ($hostlist | where {$_.name -match $hostname} | %{$_.parent.value})}).name
$row.hostname = $hostname
$row.VMKernelMemGB = $VMKernelMem
$row.FreeMemGB = $FreeMem
$row.PagesharedGB = $Pageshared
$row.PageZeroGB = $PageZero
$report += $row
}
Disconnect-viserver -confirm:$False
$report | export-csv c:\temp\TPSHostdata.csv
$clusterReport | select name,totalmemory | export-csv c:\temp\TPSClusterData.csv

Oct 292014
 

#The following is a good starting template if you have a software suite that uses web based rest APIs.
#** Note,  using Powershell version 4 is highly recommended if the API requires HTTPS and/or uses Self Signed Certs.
# Be sure to edit the user,password and URL below.

# This single line helps get around Cert issues that can prevent you from connecting to the server.  Only use this line if you have connectivity or SSL issues.
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

#The Vars and code:
$User = “testUsername”
$PWord = ConvertTo-SecureString –String “testPassword” –AsPlainText -Force
$Cred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord

$wc = New-Object System.Net.WebClient
$wc.Headers.Add(“Authorization”, “Basic $( [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(“$($Cred.UserName.TrimStart(‘\’)):$($Cred.GetNetworkCredential().Password)”)) )”)
$temp = $wc.DownloadString(“https://TheApiServer.com/api/”)
$temp

#From here you can use the $temp var to dig further into the API and then format what output you want.   You can review one of my older posts if you need help creating a report for easy exporting. If the API posts back something usable you can just use one of the many powershell Export- functions.

Sep 052014
 

This Script will clone an existing vDS and its port groups.  **with new UUIDs**
This is great if you get a corrupted vDS and need to migrate away from it.
Or, if you want to recreate a new vDS in the image of an old one without using the export/import method.

** quick notes:
- This creates a new distributed switch and port groups with new IDs.  This isn’t good to use as an Export/Import when migrating hosts and VMs to a new vCenter.
- This script does not keep special Security Policies but its very easy to add it to the script. I left all of the vars complete so you can pull and assign the extension data for additional needs.
- This code pulls an old vDS and its port groups, then recreates a new one using a “-2″ at the end of the names.  At the very end of the script, it then removes the “-2″ from the names.   Keep this in mind if you have “-2″ in the name of your vDS or port groups.  If you do use this “-2″ string in your existing names, change it in the script to something like “QQQQ” so you can remove the trailing text at the end without impacting your existing names.

## Set your old vDS name and paste the rest.

Add-PSSnapin VMware.*
Connect-VIServer vcenter.pcli.me
$oldVDSName = “dvs-MyvDS”

#Grab the old vDS info
$oldvDS = get-VDSwitch $oldVDSName

#Create the new one and rename its uplink
$newvDS = new-vdswitch -name ($oldvDS.name+”-2″) -location $oldvDS.datacenter.name -NumUplinkPorts $oldvDS.NumUplinkPorts -mtu $oldvDS.Mtu
$oldUpLink = $oldvDS | get-vdportgroup | where {$_.IsUplink -eq “True”}
$newvDS | get-vdportgroup | where {$_.IsUplink -eq “True”}  | set-vdportgroup -name ($oldUpLink.name+”-2″) -vlantrunkRange $oldUpLink.VlanConfiguration

#Pull the old vDS port groups and recreate them on the new vDS
$Portgroups = $oldvDS | get-vdportgroup | ?{$_.IsUplink -ne “True”}
foreach($port in $portgroups){
$Pname = $port.name + “-2″
$PVlanid = $port.VlanConfiguration.vlanid
$pNumPorts = $port.numports
if($port.VlanConfiguration.vlanid){
$newvDS | New-VDPortgroup -Name $Pname -Vlanid $PVlanid -numports $pNumPorts
}else{
$newvDS | New-VDPortgroup -Name $Pname -numports $pNumPorts
}
}

#####
#Here you can migrate ESXi Host links and VMs from your old vDS to your new vDS.
#If you want to migrate to the new vDS, you can get some code help here : http://www.pcli.me/?p=64
#If you copied the vDS to the same vCenter, keep in mind that vDS names and vDS Port group names are vcenter unique.
#You will need to delete your old vDS or rename it to remove the “-2″ from the new one.
#####

#Remove the old vDS if you no longer need it - Do this Manual so you can verify that everything has migrated…
#$oldvDS | remove-vdswitch -confirm:$False

#rename the new vDS and its port groups to match the orginal.
$newvDS | set-vdSwitch -name ($newvDS.name -replace “-2″,””)
$Portgroups = $newvDS | get-vdportgroup

foreach($port in $portgroups){
$port | set-vdportgroup -name ($port.name -replace “-2″,””)
}

 

#####
#Here is some extra code to set the Teaming Load Balancing policy for all port groups on your new vDS. This is configured to set all port groups to “Route based on Physical NIC load”
#####
#Change the port group load policy to Load based
$newvDSPortgroups = get-VDSwitch $newVDS | get-vdportgroup
Function Set-VDPortGroupTeamingPolicy {
param (

[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
$VDPortgroup
)
Process {
$spec = New-Object VMware.Vim.DVPortgroupConfigSpec
$spec.configVersion = $VDPortgroup.ExtensionData.Config.ConfigVersion
$spec.defaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting
$spec.defaultPortConfig.uplinkTeamingPolicy = New-Object VMware.Vim.VmwareUplinkPortTeamingPolicy
$spec.defaultPortConfig.uplinkTeamingPolicy.inherited = $false
$spec.defaultPortConfig.uplinkTeamingPolicy.policy = New-Object VMware.Vim.StringPolicy
$spec.defaultPortConfig.uplinkTeamingPolicy.policy.inherited = $false
$spec.defaultPortConfig.uplinkTeamingPolicy.policy.value = “loadbalance_loadbased”
$VDPortgroup.ExtensionData.ReconfigureDVPortgroup_Task($spec)
}
}

foreach($port in $newvDSPortgroups){
$port| Set-VDPortgroupTeamingPolicy
}

 

Sep 022014
 

Quick Report script to find those VMs that span more than one Numa Boundary.
Meaning:  If your ESX host has two – quad core CPUs and your VM is configured for six vCPUs,  then your VMs is spanning two NUMA boundaries.
Also, if your VM is configured with 32GB of memory but you only have 24GB of ram Per CPU Socket, your VM will cross memory NUMA boundaries!

Add-PSSnapin VMware.*
$report=@()

Connect-VIServer myvcenter.pcli.me

$temp = get-view -viewtype virtualmachine -property name,runtime.host,config.hardware
$temphost = get-view -viewtype hostsystem -property name,hardware.cpuinfo,hardware.MemorySize
foreach($a in $temp){
$row = “” | select VMname,VMTotalvCPUs,VMSockets,VMCores,CPUCalcNumaNodes,MemCalcNumaNodes
$row.VMname = $a.name
$row.VMTotalvCPUs = $a.config.hardware.numcpu
$row.VMsockets = ($a.config.hardware.numcpu)/($a.config.hardware.NumCoresPerSocket)
$row.VMcores = $a.config.hardware.NumCoresPerSocket
$t = $temphost | where {$_.moref -eq $a.runtime.host}
$nodesCalc = try{[system.math]::ceiling($a.config.hardware.numcpu /($t.hardware.cpuinfo.numcpucores / $t.hardware.cpuinfo.NumCpuPackages))}catch{}
$row.CpuCalcNumaNodes = if($nodesCalc -gt $t.hardware.cpuinfo.NumCpuPackages){$t.hardware.cpuinfo.NumCpuPackages}else{$nodesCalc}
$nodesCalc = if(((($t.hardware.memorysize)/1048576)/$t.hardware.cpuinfo.NumCpuPackages) -lt ($a.config.hardware.MemoryMB)){$nodescalc + 1}else{$nodescalc}
$row.MemCalcNumaNodes = if($nodesCalc -gt $t.hardware.cpuinfo.NumCpuPackages){$t.hardware.cpuinfo.NumCpuPackages}else{$nodesCalc}
$report += $row
}

### format the below output as needed.  It currently reports any VMs that span across more than one NUMA boundary.
$report | where {($_.CPUCalcNumaNodes -ge 2) -or ($_.MemCalcNumaNodes -ge 2)} | ft

 

 

 

Aug 072014
 

Some Quick One-Liners to help with Day to Day changes.  Copy and Adapt as needed.

Quick Notes***
Ram and HardDisk Capacity numbers are in GB.   The bottom code to increase a VMs existing HardDisk has a WMI call to get the Drive letters (For Windows VMs).  This will help match Hard Disk to Drive letter before you issue the last command to expand it.

####### Edit your VM name here #######
$theVM = get-vm “MySuperCoolVM”

######Increase vCPU#######
$thevm | set-vm -numcpu “3″ -confirm:$false

#######Increase RAM#######
$thevm | set-vm -memoryGB “8″ -confirm:$false

#######Rename to old_X and move to old folder
$thevm | set-vm -name (“old_”+($thevm.name)) -confirm:$false
$thevm | move-vm -destination (get-folder “old”)

#######add new Drive to VM#######
$thevm |new-harddisk -capacityGB “50″

#######increase drive on VM#######
$thevm | get-harddisk | select name,capacityGB,filename

$report = @()
$temp = get-WmiObject win32_logicaldisk -Computername ($thevm.name)
foreach($b in ($temp | where {$_.drivetype -eq “3″})){
$reportrow = “” | select VMname, DriveLetter, VolumeName,CapacityGB, FreespaceGB,percentFree
$reportrow.vmname = $thevm.name
$reportrow.driveletter = $b.DeviceID
$reportrow.VolumeName = $b.VolumeName
$reportrow.capacityGB = “{0:N3}” -f ($b.Size / 1073741824)
$reportrow.freespaceGB = “{0:N3}” -f ($b.FreeSpace / 1073741824)
$reportrow.percentfree = [System.Math]::floor(($b.FreeSpace / $b.Size)*100)
$report += $reportrow
}

$report | ft

$thevm | get-harddisk | where {$_.name -eq “Hard disk 3″} | set-harddisk -capacityGB “50″ -confirm:$false

 

Jul 242014
 

#Upgrading a cluster from 5.1 to 5.5 or even updating past the Heart Bleed and need a quick double check that all of the host got the new build?
#I throw this at the entire vcenter but you can narrow it down to per datacenter or cluster if you like…

### Here is the quick (cluster only) code…

$Report = @()
get-cluster myCluster | get-vmhost | %{
$vmhost = Get-View $_.ID
$ReportRow = “” | Select-Object Hostname, build
$ReportRow.Hostname = $vmhost.Name
$ReportRow.Build = $vmhost.summary.config.product.build
$Report += $ReportRow
}
$report | FT

 

### If you want to be more fancy, here is a multi vCenter scan… (check ALL the hosts!)

Add-PSSnapin VMware.VimAutomation.Core

$vcenters = @()
$vcenters += “vcenter1″
$vcenters += “vcenter2″
$vcenters += “vcenter3″

$Report = @()
foreach($vcenter in $vcenters){
Connect-VIServer $vcenter

$clusters = get-cluster
foreach($a in $clusters){
$a | get-vmhost | %{
$vmhost = Get-View $_.ID
$ReportRow = “” | Select-Object vcenter,cluster,Hostname, build
$ReportRow.vcenter = $vcenter
$ReportRow.cluster = $a.name
$ReportRow.Hostname = $vmhost.Name
$ReportRow.Build = $vmhost.summary.config.product.build
$Report += $ReportRow
}
}
Disconnect-viserver -confirm:$False
}
$report | FT

Jul 072014
 

#this code will scan all hosts in your vcenter and check for duplicate IPs. You can narrow the scan by placing a get-cluster or get-datacenter object when loading the “$thedata” var.

$thedata = get-vmhost | Get-VMHostNetwork | Select Hostname, VMkernelGateway -ExpandProperty VirtualNic
$report = @()
$temp = $thedata | %{$_.ip}
$h = @{}
$temp | foreach {$h["$_"] += 1}
$dups = $h.keys | where {$h["$_"] -gt 1}
foreach($a in $dups){
$report += $thedata | where {$_.ip -eq $a} | select hostname,ip,ManagementTrafficEnabled,VMotionEnabled
}
$report | ft

######
#sample output :
#HostName     IP                        ManagementTrafficEnabled       VMotionEnabled
#———-         ———-             ———                                             —————-
#esx01              192.168.0.101    False                                                True
#esx06             192.168.0.101    False                                                 True

#if you want the report to include more information you can edit the “report +=” line and add extra fields  (to the select area).
#example : You can add the Devicename and PortGroupName if you need help finding the exact vmk with the dup IP.
$report += $thedata | where {$_.ip -eq $a} | select hostname,ip,devicename,portgroupname,ManagementTrafficEnabled,VMotionEnable

Jun 062014
 

This code will pull the list of vlans on your vDS trunk, pull the vlans of each port group on the vDS, then compare the two to find any misconfigurations.
This can help identify if any vDS Trunk is missing vlans (for vDS healthcheck to work right.)
OR
Help find vDS objects that have a vlan configured on the trunk but no port group to use it.
– Ultimately.. this is a Health Check for the vDS Health Check.

$report = @()
$vds = get-vdswitch

foreach($a in $vds){
$pgs = $a | get-vdportgroup
$uplinkvlans = @()
$uplinkvlantypecheck = $pgs| ?{$_.name -like “*Uplinks*”} | %{$_.VlanConfiguration.vlantype}
if($uplinkvlantypecheck -eq “Trunk”){
$uplinkvlanrange = $pgs| ?{$_.name -like “*Uplinks*”} | %{$_.VlanConfiguration.ranges}
foreach($b in $uplinkvlanrange){
if($b.StartVlanId -eq “0″ -and $b.EndVlanId -eq “4094″){$report += $a.name + ” Trunk is configured with ALL VLANs — 0-4094″ }else{
$start = $b.StartVlanId
$end = $b.EndVlanId
$uplinkvlans += $start..$end
} #end Else
} #end foreach vlan on trunk
} #end if trunk
else{$uplinkvlans = $pgs| ?{$_.name -like “*Uplinks*”} | %{$_.VlanConfiguration.vlanid}
} #end else

#end uplink vlan collection

$vmPGs = $pgs | ?{$_.name -notlike “*Uplinks*”}
$pgvlans = @()
foreach($apg in $vmPGs){
if(($apg.VlanConfiguration.vlantype) -eq “Trunk”){
$pgvlanrange = $apg | %{$_.VlanConfiguration.ranges}
foreach($b in $pgvlanrange){
$start = $b.StartVlanId
$end = $b.EndVlanId
$pgvlans += $start..$end
} #end foreach vlan in PG
} #end if trunk
else{$pgvlans += $apg| %{$_.VlanConfiguration.vlanid}
} #end else
} #end port group vlan collection

$pgvlans = $pgvlans | select -unique
$checkit = Compare-Object $uplinkvlans $pgvlans
if($checkit.inputobject.count -gt 0){
foreach($aa in $checkit){
if($aa.sideindicator -eq “<="){$texta = "PortGroup"}
if($aa.sideindicator -eq "=>“){$texta = “Trunk”}
$report += $a.name + ” ” +$texta+” is missing vlan “+ $aa.inputobject
}
}
}
$report

Jun 042014
 

So you want to Pin a VM to a host huh?
Maybe for some network mirror or span port entertainment?

Here is how you do it pcli style:

#set your vars:

$thecluster = “pcli-cluster1″
$thevmhost = “esx1.pcli.me”
$thevm = “vm1″
$VMGroupName = “MyVMGroupName”
$HostGroupName = “MyHostGroupName”
$rulename = “MyAffinityRuleName”

#paste the code:

#VMGroup
$cluster = Get-Cluster $thecluster | Get-View
$spec = New-Object VMware.Vim.ClusterConfigSpecEx
$group = New-Object VMware.Vim.ClusterGroupSpec
$group.operation = “add”
$group.Info = New-Object VMware.Vim.ClusterVmGroup
$group.Info.Name = $VMGroupName
Get-VM -Name $theVM | %{$group.Info.VM += $_.Extensiondata.MoRef}
$spec.GroupSpec += $group
$cluster.ReconfigureComputeResource_Task($spec,$true)
#HostGroup
$spec = New-Object VMware.Vim.ClusterConfigSpecEx
$group = New-Object VMware.Vim.ClusterGroupSpec
$group.operation = “add”
$group.Info = New-Object VMware.Vim.ClusterHostGroup
$group.Info.Name = $HostGroupName
Get-VMHost -Name $TheVMHost | %{$group.Info.Host += $_.Extensiondata.MoRef}
$spec.GroupSpec += $group
$cluster.ReconfigureComputeResource_Task($spec,$true)
#Make the Rule
$spec = New-Object VMware.Vim.ClusterConfigSpecEx
$rule = New-Object VMware.Vim.ClusterRuleSpec
$rule.operation = “add”
$rule.info = New-Object VMware.Vim.ClusterVmHostRuleInfo
$rule.info.enabled = $true
$rule.info.name = $RuleName
$rule.info.mandatory = $true
$rule.info.vmGroupName = $VMGroupName
$rule.info.affineHostGroupName = $HostGroupName
$spec.RulesSpec += $rule
$cluster.ReconfigureComputeResource_Task($spec,$true)

I’m sure someone can reduce the code but I left it broken out here to provide the section view.
IE : If you only want to create a Host group, take the middle part of the script.