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/”)

#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
$newvDS | New-VDPortgroup -Name $Pname -Vlanid $PVlanid -numports $pNumPorts
$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 (

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”

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.*

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        False                                                True
#esx06       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.)
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

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:

$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
$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
#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

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.

May 272014

#Looks like playing with vFlash can cause some vCenter Webclient issues….
#KB = http://kb.vmware.com/kb/2072392

#If you want to “remove” all vflash from your hosts so you can get things working again, you can use PowerCLI.
#1 – Download the “Extensions” for vflash (and vsan) here
– - https://labs.vmware.com/flings/powercli-extensions
#2 – Place that folder into your powershell > Modules directory.
– - The most common places is : C:\Windows\System32\WindowsPowerShell\v1.0\Modules
#3 – Import the Extensions : Import-Module VMware.VimAutomation.Extensions
#4 – Verify that the Extensions loaded : get-command -Module VMware.VimAutomation.Extensions
– - Output should show ten new command-lets
#5 – Review your current vFlash config :
– - $hosts = get-cluster pcli.me | Get-VMHost
– - Get-VMHostVFlashConfiguration -VMHost $hosts
– - Output will look close to this:
– - – Name CapacityGB SwapCacheReservationGB Extents
– - – esx1.pcli.me 731 0 {eui.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:P1}
– - – esx2.pcli.me 731 0 {eui.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:P1}

#6 – Remove the config with this command (you can make it smaller but this command worked best for me)
– - get-vmhost esx1.pcli.me| get-VMHostVFlashConfiguration | Set-VMHostVFlashConfiguration -RemoveVFlashResource
– - get-vmhost esx2.pcli.me| get-VMHostVFlashConfiguration | Set-VMHostVFlashConfiguration -RemoveVFlashResource

#7 – Then to verify that things are removed, throw another Get-VMHostVFlashConfiguration -VMHost $hosts