vSphere focused Powershell snippets

How many times have you came across a scenario where you know you’ve solved with some Powershell code in the past, but can’t remember which cmdlet, flag or syntax you used?

I’ve done this to myself countless times, so over the last couple of months I’ve made a conscious effort to centrally write down snippets of code that I’ve used, so future me will be grateful for (helping me save time and some sanity also).

Below are some snippets of code that you may find useful in your day to day tasks as a vSphere admin. Some of these examples would’ve been pinched from other blogs and others I’ve crafted myself. I’ve tried to reference the original blog where possible.


Virtual Machine Operations

Removing snapshots:
The csv should contain headers vmname and snapname which I just grab from RVTools. This will go through and delete one snapshot at a time, if you’re a gambler, you can do them all at once by adding -RunAsync but I would not recommend it in production.

$vms = Import-csv .\snaps.csv
$vms | %{Get-Snapshot $_.vmname -name $_.snapname | Remove-snapshot -confirm:$false}

The above code is good if you want to target specific snapshots for VMs, but if you want to remove all snapshots against a VM, a slight modification to the above code, show below will work. The CSV you pass in here should only contain a list of VM names:


foreach ($vm in $vmList) {Get-Snapshot $vm | Remove-Snapshot}

Note: Previously we had a $vm | % {… instead of a foreach statement. % is short for foreach and we are passing in the list of VMs into it.

Deploy OVF with customizatons
If you need to deploy a few instances of the same appliance with some customizations, this is really helpful.

First you need to import the OVF and extract the varaibles that are available for customization

$ovfpath = ".\VendorAppliance.ova"
$ovfconfig = Get-OvfConfiguration -ovf $ovfpath
$ovfconfig.ToHashTable() | FT -autosize

Once you have this, you can pick out which ones you need to customize and declrate the values as below.

$ovfconfig.NetworkMapping.primary.Value = "CLS01_VL3"
$ovfconfig.NetworkMapping.mon0.Value = "CLS01_Monitor"
$datastore = "cls01_fcp"
$esxhost = "esxi01.vkarps.local"
$vmname ="AppServer"
$DRSRulename = "AppServer1tohost1"
$HostRule = "Host1"
$cluster = "CLS01"

Once that it all done, it’s time to deploy the appliance
Import-VApp $ovfpath -OvfConfiguration $ovfconfig -name $vmname -VMHost $esxhost -Datastore $datastore

Prevent tools from re-sizing display
(https://vkarps.wordpress.com/2018/07/30/vm-console-display-resizing/)


$vmname = "KioskVM"
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
$opt = New-Object VMware.Vim.OptionValue
$opt.Key = "guestInfo.svga.wddm.modeset"
$opt.Value = "FALSE"
$spec.ExtraConfig += $opt
$vm = Get-VM -Name $vmName
$vm.ExtensionData.ReconfigVM($spec)

Move single VM to defined folder

$vmfolder = "SQL"
Move-VM -vm SQL01 -destination $vmfolder

Move multiple VMs to defined folder

$vmFolder = "SQL"
$vms = import-csv vms.csv
Foreach ($vm in $vms){Move-VM -vm $vm -destination $vmfolder}

Move VMs from one datastore to another

$vms = Get-datastore "cls01_vol01" | Get-VM
foreach($vm in $vms){
Move-VM $vm.name -Datastore "cls01_vol02"
}

Move list of virtual machines to a defined host

$vms = Import-csv .\SQLVMs.csv
foreach($vm in $vms){
Move-VM $vm.name -Destination "esxi01.vkarps.local"
}

AutoDeploy

Create new deploy rule with image profile
If you want to create a new AutoDeploy rule, there is no commandlet that I’ve found (as of writing this) that will list out the image profile objects from the repository. The way we get around this is by grabbing the image profile from an existing host that already has the image applied, then passing that object into the New-DeployRule command.

$img = Get-VMHostImageProfile esxi01.vkarps.local
New-DeployRule -Name DeployRuleName -Item $img,Cluster1 -Pattern "ipv4=10.1.1.100-10.1.1.104"

Copy and existing Autodeploy rule and set some new patterns
This is useful if you want to use an existing image or host profile and apply it to a new target / pattern. You could also use this to solve the same issue that the previous code did.

Copy-DeployRule -DeployRule "testrule" -ReplaceItem host_profile,targetcluster -ReplacePattern "ipv4=192.XXX.1.10-192.XXX.1.20"

Forcing a compliance update
So, if you’ve ever played with AutoDeploy you will know it has some annoying ‘features’. One is when you’re changing an image profile for a deploy rule, the host won’t automatically pick up that change on the next reboot (in my experience anyway). The below snippet will force the AutoDeploy service to refresh it’s mappings for the target host.

Test-DeployRuleSetCompliance -VMhost esxi01.vkarps.local | Repair-DeployRuleSetCompliance

Host Operations

Create a new VMKernel port
Enabling vMotion with JumboFrames in this example

New-VMHostNetworkAdapter -VMHost esxi01.vkarps.local -PortGroup Cluster1_VMK_10.1.2.0_VL2_vmotion -VirtualSwitch Cluster1_vds -IP 10.1.2.100 -SubnetMask 255.255.255.0 -Mtu 9000 -vmotionenabled $true

Mounting an NFS datastore to a host
New-Datastore -Nfs -VMHost esxi01.vkarps.local -Name cls1_syno_vol01 -Path "cls1_syno_vol01" -NfsHost 10.1.3.10

Mounting an NFS datastore to all hosts in cluster

$hosts = Get-Cluster "CLS01" | Get-VMHost
foreach($hst in $hosts){
New-Datastore -Nfs -VMHost $hst.name -Name cls1_syno_vol01 -Path "cls1_syno_vol01" -NfsHost 10.1.3.10
}

Set dump collector configuration for defined cluster

$cluster = CLS01
Get-Cluster $clsuter | Get-VMHost | Set-VMHostDumpCollector -HostVNic "vmk0" -NetworkServerIP "10.1.1.111" -NetworkServerPort 6500

Configure Multipathing policy variants
You may have a scenario that a number of hosts across clusters have a particular lun set to fixed path and you need to set it to round robin. The below snippet will do that for the defined scsi lun

$hosts = Import-csv .\FixedPathHosts.csv
Foreach ($h in $hosts){
Get-VMhost $h.name | Get-ScsiLun naa.6000155000000010b000801ebeaaaa50 | Set-ScsiLun -MultipathPolicy "roundrobin"
}

Similar to above, but for all hosts in the clusters
Get-Cluster CLS01 | Get-VMhost | Get-ScsiLun naa.6000155000000010b000801ebeaaaa50 | Set-ScsiLun -MultipathPolicy "roundrobin"

For a single ESXi host, but any lun stating with naa.600

Get-VMHost esxi01.vkarps.local | Get-ScsiLun -CanonicalName "naa.600*" | Set-ScsiLun -MultipathPolicy "roundrobin"

Reporting

We all often get asked to report on various and perhaps obscure things. Here are some that I’ve found I either regularly get asked for or have found handy to extract data quickly.

VM Properties
Sometimes you may need to get some metadata about a list of VMs for folks, below is an example of taking a list of VMs and finding out which hosts they are currently running on and spitting out the result to a file. It can be easily modified to find different VM properties.

$vmList = Get-Content vm.txt
$output = foreach ($vmName in $vmList) {Get-VM $vmName | Select-Object -Property Name,VMHost}
$output | Export-Csv c:\temp\VMHostList.csv

DRS Groups
Say you need to get the specs (or attributes) of virtual machines in a DRS Group. Below is an example of how to grab a list of objects in a DRS group and find the specs we are interested in (vCPU count and Memory allocation).

$a=(get-DRSClusterGroup -cluster Cluster2 -Name "SQL VMS")
$b=$a.vm
$c= foreach ($vm in $b) {get-VM $vm | Select Name, NumCPU,MemoryGB }
$c | export-csv Cluster2_sqlVMs.csv

compare object (DRS group to what’s on the host)
If you have some “License restrictions” in your environment, you may have to force a number of VMs onto a single or gorup of hosts using DRS groups. It’s quite hard to maintain a DRS rule that negates the first rule. I.e: Anything not in group “SQL” group, do not put it onto “SQL Host” host.
I found the below snippet helpful to compare the VM DRS Group to what is actually running on the host. It is much quicker than uing a spreadsheet or going through it manually. The compare-object cmdlet can be used for a number of use cases.


$a = get-cluster CLS01 | Get-DrsClusterGroup -name "SQL Guests" | Select member
$b = Get-VMHost esxi01.vkarps.local | Get-VM | Select name
$a.member.name.count (This line and the one below are not required, just gives you an indication if you need to run the last line or not. I.e if they're the same, you're good; in this scenario).
$b.count
compare-object $a.member.name $b.name

Get datastore mount path (NFS)

Get-VMHost esxi01.vkarps.local | get-Datastore | Select Name,@{n='RemoteHost';e={$_.RemoteHost[0]}},RemotePath | Export-csv CLS01_NFS_DatastoreDetails.csv -NoTypeInformation

Get datastores / datastore cluster relationship

Get-Datastore -Location DC2 | Select @{N=’DSC’;E={Get-DatastoreCluster -Datastore $_ | Select -ExpandProperty Name}},Name

Check which port groups have netflow enabled on vDS

Get-vDSwitch clos01_vds | Get-vDPortGroup | Select Name,@{Name="NetflowEnabled";Expression={$_.Extensiondata.Config.defaultPortConfig.ipfixEnabled.Value}}

Get dump collector config for cluster

Get-Cluster CLS01| Get-VMHost | Get-VMHostDumpCollector | FT VMHost,Hostvnic,NetworkServerIP,NetworkserverPort,Enabled

List VMs with ISO mounted in Cluster

Get-Cluster CLS01 | Get-VM | Select Name, @{Label="ISO file"; Expression = { ($_ | Get-CDDrive).ISOPath }} | Export-csv -NoTypeInformation CLS01MountedMedia.csv

Get Power on events for defined VM
This can be adjusted to look at other tasks. Great writeup here with some more detail http://www.lucd.info/2009/11/18/events-dear-boy-events-part-2/


Get-VM SQL01 | Get-VIEvent -MaxSamples ([int]::MaxValue) | where { $_.fullFormattedMessage -like "Task: Power on*" }

Get VM DNS name for VMs with particular string in the name

Get-VM | Where {$_.name -like "*SQL*"} | Select name, @{N="DnsName"; E={$_.ExtensionData.Guest.Hostname}} | FT -autosize

Get VM count for each host and export to csv

Get-VMHost | Select @{N=“Cluster“;E={Get-Cluster -VMHost $_}}, Name, @{N=“NumVM“;E={($_ | Get-VM).Count}} | Sort Cluster, Name | Export-Csv -NoTypeInformation c:\HostVMCount.csv`

Get vMotion events for particular Virtual Machines and export to csv
Ensure you have the Get-VMotion script installed on your machine (see http://www.brianbunke.com/blog/2017/01/03/get-vmotion/)

Import-Module Get-vMotion
$vms =@('SQL01','SQL02');
$array = @()
foreach($vm in $vms){
$array += get-VM $vm | Get-vMotion -days 30 | Select Name,srcHost,dstHost,Duration,StartTime,EndTime
}
$array | Export-csv -NoTypeInformation .\vMotionEvents.csv

Get VMs Sync Time With Host Setting

Get-VM * | Select @{N='VM Name';E={$_.Name}},@{N='GuestOS';E={$_.ExtensionData.Guest.GuestFullName}},@{N='SyncWithHost';E={$_.ExtensionData.Config.tools.SyncTimeWithHost}} | Export-csv .\timeSync.csv -NoTypeInformation

vDS Operations

Creating a new port group on an existing vDS
In this example we are setting the “Allow Promiscuous” flag to the port group.
$vds = Get-VDSwitch "cls01_vds"
$pg = "cls01_monitor"
$vdspg = $vds | New-VDPortgroup -name $pg
$vdspg | Get-VDSecurityPolicy | Set-VDSecurityPolicy -AllowPromiscuous $true

Export vDS config

$vDSConfLocation = "C:\vDSConfigs"
$vDS = "CLS01_vds"
Get-VDSwitch -name $vDS | Export-VDSwitch -Description “Backup of $($_.Name) VDS” -Destination "$vDSConfLocation\$vDS$($_.Name).Zip" -Force

Create new vDS based off existing one in different vCenter
This can be easily adjusted to copy from within the same vCenter

$srcvCenter = "vc01.vkarps.local"
$dstvCenter = "vc02.vkarps.local"
$DCLocation = "DC2"
$vDS = "CLS01_vds"
$srcVDS = Get-vDSwitch $vDS
$srcPG = $srcvDS | Get-VDPortgroup
New-VDSwitch -Server $dstvCenter -name $vds -Location (get-Datacenter -Server $dstvCenter $DCLocation) -LinkDiscoveryProtocol CDP -LinkDiscoveryProtocolOperation Listen -Mtu $srcVDS.mtu -NumUplinkPorts $srcVDS.NumUplinkPorts -Version 6.5.0
Foreach ($pg in $srcPG)
{
$pgVLAN = $pg.Extensiondata.Config.DefaultPortConfig.Vlan.VlanID
If ($pg.IsUplink -eq "True"){Write-Host "Skipping Uplink PortGroup" -ForegroundColor yellow}
#If it is not the uplink pg, create it
else{
Get-VDSwitch -Server $dstvCenter -name $vDS | New-VDPortgroup -Name $pg.name -NumPorts $pg.numPorts -VLanId $pgVLAN
}
}

Cluster Operations

Create VM DRS Group and add a VM

$vmname = "SQL01"
New-DrsClusterGroup -Name "SQL VMs" -cluster $cluster -vm $vmname

Create Host DRS group and add host

$esxhost = "esxi01.vkarps.local"
New-DrsClusterGroup -Name "Host1" -cluster $cluster -VMHost $esxhost

Create new VM/Host rule from previously created groups

$DRSRulename = "SQL Licensing"
$vmGroup = "SQL VMS"
$hostRule = "Host1"
New-DrsVMHostRule -Name $DRSRulename -Cluster $cluster -VMGroup $vmGroup -VMHostGroup $HostRule -Type "MustRunOn"

Create new cluster based off a cluster in different vCenter

$cluster = "CLS01"
$srcCluster = Get-cluster -name $cluster
$DCLocation = "DC2"
$dstvCenter = "vc01.karps.local"
$srcvCenter = "vc02.vkarps.local"
New-Cluster -Server $dstvCenter -name $srcCluster.name -Location $DClocation -DRSEnabled -DRSAutomationLevel $srcCluster.DRSAutomationLevel -EVCMode $srcCluster.EVCMode -HAEnabled

Datastore Operations

Create Datastore Cluster and disable SIOC

New-DatastoreCluster -Name $dsCluster -Location $DCLocation

Set SDRS to manual and disable SIOC on Datastore Cluster

Set-Datastorecluster -sdrsAutomationLevel Manual -IOLoadBalanceEnabled $false

Create folder under datastores view under existing folder

(get-view (get-view -ViewType datacenter -Filter @{"name"="DC2"}).DatastoreFolder).CreateFolder("SQL")

I hope that some of these examples have been useful to you or perhaps given you a better idea on how you can use powershell for particular use cases, where you can then adopt it to your use case.

That’s all I have for now, I’ll eventually put this into github and keep adding to it there. If you have any feedback, please leave a comment below.

Advertisements

Disable VM console display resizing

The other day my attention was drawn to an odd behavioural change when connecting to a VM using the VMware console, Web or Remote. This particular customer had an application which requires a specific resolution in order to function properly. When a user would open the remote console, it would automatically re-size the resolution to fit the window size. The behaviour was noticed shortly after an upgrade from vCenter 5.5 to VCSA 6.5, so the end users were not as fond of the VCSA as I was.

Attempting to force the resolution using the method defined in KB2058577 didnt help either as it would resize as soon as the window was modified. I was unable to find any other articles that had a permentant fix.

I got on the phone to support and didnt get much further, but they suggested updating tools to a newer version, so I went over to the release notes of some of the newer versions. Now, I am not entirely sure what introducted this behaviour, but what I do know is that in the release of VMware Tools 10.2.5 an option to disable the behavior was added.

To disable the auto resizing, add the advanced paramater guestInfo.svga.wddm.modeset="FALSE" to the virtual machine which is documented in KB53572.

Below are the steps that solved the problem for me:

  • Update VMware tools to 10.2.5
  • Set resolution to desired size using method in KB2058577 (This is to ensure the VM does not get stuck in a resolution it may have auto-sized to previously)
  • Shutdown VM
  • Upgrade VM hardware if required ( versions before 7 had a lower graphic memory allocation, will depend on your resolution, good opportunity to do it while the VM is offline)
  • Configure advanced option, PowerCLI method below:
$vmname = "AppServer-01"

$spec = New-Object VMware.Vim.VirtualMachineConfigSpec

$opt = New-Object VMware.Vim.OptionValue

$opt.Key = "guestInfo.svga.wddm.modeset"

$opt.Value = "FALSE"

$spec.ExtraConfig += $opt

$vm = Get-VM -Name $vmName

$vm.ExtensionData.ReconfigVM($spec)

Once you power on the VM, it should retain the previously set resolution when you resize your remote console window. Note that you can force the resolution setting via group policy and probably skip the step to resize the resolution.

Migrating ESXi Hosts with a vDS between vCenter servers using Powershell

Most vSphere admins are probably in the process of moving over to to vSphere 6.x or planning for it as end of general support for vSphere 5.5 is appraoching later this year.
I wrote about how to go about migrating from the Windows vCenter 5.5 to the VCSA 6.5 in an earlier post here, however that is not always an option. Some may choose to go with a greenfield deployment, which leaves you having to move your hosts over to the new environment.
There are a couple of different scenarios here, but in this post I am going to focus on what I believe to be a common one. That being, we have an existing vSphere 5.5 environment, utilizing Distributed Switches and a greenfield vSphere 6.5 environment which we want to move our hosts and VMs over to.

Now, there are a few posts out there that do this quite easily, but as they point out its not an officially supported method by VMware, KB here. The supported steps are outlined but as you can quickly see, that is a lot of clicking when you have a moderate to large number of hosts. Having to do this for a customer with a few hundred hosts, I wasnt even going to entertain the idea of doing it all manually, so I came up with a couple of scripts ( with the help of some code that was published by vmware community members).
I split up the scripts into two parts:

Part 1 – Migrating the host and VMs from the vDS to a newly created vSS
Part 2 – Moving the host between vCenter servers and migrating it to a vDS

I have made the assumptions that the vSphere 6.5 environment has already had the target constructs already created (i.e Clusters, vDS, Folders, etc). Also that the management kernel port already resides on a seperate standard switch.

I have not included any automation for host profiles and autodeploy, but I plan to put out another post which covers the environments which utilize those features.

Enough rambling, here are the scripts:
Part 1 here
Part 2 here

Lets take a look and breakdown the code:

Part 1:

First we have to define a couple of variables which outline what we want to target:

#The vCenter server to connect to
$srcvCenter = "VC01.karpslab.local"
#The target Host
$vmHost = "ESXi-01.karpslab.local"
#Name of the first physical adapter we want to target
$pNIC1 = "vmnic2"
#Name of the second physical adapter we want to target
$pNIC2 = "vmnic3"
#Name of the distributed switch we want to move away from
$vDS = "vDS-Cluster-01"
$vSS = "MigSwitch" #Name of the temporary vSwitch that we create
#name of the VMK1 port group
$vmk1pg = "vDS-Cluster-01-VL10-NFS"
#name of the VMK2 port group
$vmk2pg = "vDS-Cluster-01-VL20-vMotion1"
#name of the VMK3 port group
$vmk3pg = "vDS-Cluster-01-VL20-vMotion2"

It is really important to note that the VMKernel port number lines up with the correct port group here, otherwise you will run into problems. If you have more VMkernel ports, you can quite easily add extra variables here and in the section where we migrate them over later in the code.

Next the script connects us to the defined vCenter server, after which we grab the details of our vDS and its port groups and place them into variables.

$vDSobj = Get-VDSwitch -Name $vDS
$vDSpg = $vdsObj  Get-VDPortgroup

Now we create the new Standard vSwitch, using the MTU value we got form our vDS:

$vSSObj = New-VirtualSwitch -VMHost $vmHost -Name $vss -mtu $vDSObj.mtu

Here we step through each port group in the $vDSpg variable which contains the port groups that exist on the vDS. Firstly, we get the vlan id of the port group, then check if it is the uplink port group which is created with a vDS, if it is the uplink port group, we skip that and move on. Otherwise if it is a regular port group, we then create the respective port group on the vSS we created earlier.

foreach($pg in $vDSpg){
#Get port group VLAN ID
$pgVLAN = $pg.Extensiondata.Config.DefaultPortConfig.Vlan.VlanID
#Check if it is the uplink pg
If ($pg.IsUplink -eq "True"){Write-Host "Skipping Uplink PortGroup" -ForegroundColor yellow}
#If it is not the uplink pg, create it on the vSS
else{
New-VirtualPortGroup -Name $pg.name -VirtualSwitch $vSSObj -VLanId $pgVLAN  Out-null
Write-Host "Created PortGroup $pg with Vlan ID $pgVLAN" -ForegroundColor Cyan
}
}

Now that we have the vSS configured the way we want it, we can begin to migrate the host from the vDS. Firstly we need to move one of the interfaces off the vDS and onto the vSS. In this scenario this will be “vmnic2”.

$pNIC1Obj = Get-VMHostNetworkAdapter -VMhost $vmhost -Physical -name $pNIC1 #Gets the NIC object
$pNIC1Obj  Remove-VDSwitchPhysicalNetworkAdapter -Confirm:$false #Removes adapter from vDS
Add-VirtualSwitchPhysicalNetworkAdapter -VirtualSwitch $vSSObj -VMHostPhysicalNic $pnic1Obj -Confirm:$false #adds adapter to vSS

Within the scripts I have placed blocks of code that asks the user to continue to the next step. This has been put in as there are parts where you might want to go and validate that things are workings as expected before proceeding. For example, if one of your interfaces has the incorrect VLAN configuration on the underlying switch port, you wont have much joy when you cut over a VMs network or an NFS kernel port. It does slow thing down a bit, but if you’re working on a production environment I think its a good practice. No-one wants to be the guy who brings down a business critical application because we messed up a vlan configuration or mtu size.

The while loop validates that the entry is a yes or a no. If no, the script exits.

$continue = Read-Host "Would you like to continue to migrating VM networks (Y/N)?"
while("Y","N" -notcontains $continue)
{
	$continue = Read-Host "Please enter Y or N"
}
if ($continue -eq "N")
{
Write-Host "Exiting Script" -ForegroundColor Red
break
}elseif ($continue -eq "Y")
{
Write-Host "Continuing to VM Network Migration" -ForegroundColor Green
}

So now our host should have a new vSS and one interface attached. Next we need to target the virtual machines and ensure they start communicating over the vSS and the uplink we associated with it. Before we do that, its a good idea to set the cluster DRS mode to manual. This is done with the below snippet:

#Set Cluster DRS Setting to Manual
$VMhostObj = Get-VMHost $VMhost
$ClusterObj = Get-Cluster -Name $VMhostObj.Parent
Write-Host "Setting DRS for Cluster $clusterObj to Manual" -ForegroundColor Cyan
Set-Cluster -Cluster $clusterObj -DrsAutomationLevel Manual -Confirm:$false Out-Null

Let’s move on to re-configuring the VMs to the vSS ports:

We need to get a list of the virtual machines that are currently running on the host and put them in a variable.

$VMlist = $VMhostObj | get-VM

We now loop through each vm in the list and do two things:

  1. Get the details of the current network adapter attached to the VM
  2. Set the VMs network adapter to the port group on the vSS. We do this by getting the portgroup object from the standard switch, which is the same name as the port group of the vDS.

The below code will prompt you when modifying each VM, but this can be avoided by adding -Confirm:$false at the end of the command. I suggest using a tool such as pinginfoview to validate that the VM networks cutover properly, that way you can get ontop of it quickly, should there be any issues. I have not tested this on virtual machines with mutliple interfaces (yet).

foreach ($VM in $VMlist){
$VMnic = Get-NetworkAdapter $vm
$VMnic | Set-NetworkAdapter -PortGroup (Get-VirtualPortGroup -VMhost  $VMHost -Standard -Name $vmnic.NetworkName)
Write-Host "Migrated $VM network to $vSS on $VMhost" -ForegroundColor Cyan
}

The next step is to cutover the VMkernel ports, along with the last adapter that remains on the vDS. I couldn’t find a way to do one at a time as you do when moving the other direction (vSS to vDS), but I did come across this post from @Lamw here which cuts them all over along with the adapter. I have modified it slightly for this scenario. This is also the section where you will need to add or remove vmkernel interfaces to suit your environment:

#Get pNic and swtich objects
$pNIC2Obj = Get-VMHostNetworkAdapter -VMhost $vmhost -Physical -name $pNIC2
$vSSObj = Get-VirtualSwitch -VMhost $VMhost -Name $vSS

#Get VMK ports to migrate
$vmk1 = Get-VMHostNetworkAdapter -VMhost $vmhost -VMKernel -name vmk1
$vmk2 = Get-VMHostNetworkAdapter -VMhost $vmhost -VMKernel -name vmk2
$vmk3 = Get-VMHostNetworkAdapter -VMhost $vmhost -VMKernel -name vmk3

#get VMK port groups to migrate to
$vmk1pgObj = Get-virtualportgroup -virtualswitch $vssObj -name $vmk1pg
$vmk2pgObj = Get-virtualportgroup -virtualswitch $vssObj -name $vmk2pg
$vmk3pgObj = Get-virtualportgroup -virtualswitch $vssObj -name $vmk3pg

#create array of VMKports and VMKPortGroups
$vmkArray =@($vmk1,$vmk2,$vmk3)
$vmkpgArray =@($vmk1pgObj,$vmk2pgObj,$vmk3pgObj)

#Move physical nic and VMK ports from vDS to vSS
Write-Host "Migrating $vmhost from $vds to $vss" -ForegroundColor Cyan
Add-VirtualSwitchPhysicalNetworkAdapter -VirtualSwitch $vssObj -VMHostPhysicalNic $pNIC2Obj -VMHostVirtualNic $vmkarray -VirtualNicPortgroup $vmkpgarray  -Confirm:$false

Finally, we remove the host from the vDS:

$vdsObj | Remove-VDSwitchVMHost -VMHost $vmhost -Confirm:$false 

If all goes to plan, we will now have the target host entirely on the vSS and all the VMs are still running without anyone noticing.

Now lets breakdown the script that does Part 2:

Lines 30 – 143 have two functions defined which have been writted by http://kunaludapi.blogspot.com.au. The first function Get-VMFolderPath, does exactly that, this is so we know which folder the VM was in prior to moving it. The Move-VMtoFolderPath funciton takes the output from the previous function and moved the specified list of VMs to the appropriate folder. As mentioned earlier, it is assumed that the folder structure is already created. There are a number of scripts out there that can help you export / import folder structures in vCenter.

The next part of the script defines the same variables as the previous one, although we have added the $dstvCenter and $dstCluster variables which define where we want to move the host.

Before we move the host, we need to get the VM folder list with this snippet of code:

$VMhostObj = Get-VMhost $VMhost
$VMlist = $VMhostObj | get-VM
$VMFolders = $VMlist | Get-VMFolderPath

Now, to remove the host from the current vCenter:

First we need to set it to a disconnected state, then remove it from vCenter

Set-VMhost $vmhost -State "Disconnected" | out-null
Remove-VMhost $vmhost -server $srcvCenter -Confirm:$false

Next we want to disconnect from the source vCenter and connect to the destination vCenter:

#disconnect from source vCenter
disconnect-viserver $srcvCenter -confirm:$false
#Connect to $dst vCenter
$dstVCCreds = Get-Credential -Message "Enter credentials for $dstvCenter"
if (Connect-VIServer -Server $dstvCenter -Credential $dstVCCreds -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -force) {
  Write-Host "Connected to $dstvCenter" -ForegroundColor green
}
else {
  Write-Host "Could not connect to vCenter server $dstvCenter" -ForegroundColor Red
  Write-host "Error:" -ForegroundColor red $Error[0]
  Break
}

Now that we’re connected we can add the host to the new vCenter, as we need a root password to do so, we get the users input here. This can be easily stored in a variable. See my previous post on how, otherwise there are plently of blogs out there explaining it. We also need to specify our target cluster that the host is going to be a member of.

$ESXcreds = Get-Credential -Username root -Message "Enter the root password for $vmhost"
$location = Get-Cluster $dstCluster
Add-VMhost -Server $dstvCenter -Name $vmHost -Location $location -Credential $ESXcreds | out-null

Once this host is added, all the virtual machines should be added to the inventory along with it and land in the Discovered Virtual Machines folder, we will sort this out further in the script. The next thing we need to do is to step the host into the vDS so we can migrate our VMKernel ports and VM networks over. Once again, it is assumed that you’ve already imported or re-created your vDS in the new vCenter.

#add host to vDS
$vdsObj = Get-VDSwitch $vDS
$vdsObj | Add-VDSwitchVMHost -VMHost $vmhost | Out-Null
#Migrate first adapter to vDS
$pNIC1Obj = Get-VMHostNetworkAdapter -VMhost $vmhost -Physical -name $pNIC1
$vdsObj | Add-VDSwitchPhysicalNetworkAdapter -VMHostNetworkAdapter $pNIC1Obj -Confirm:$false

As there is better support for the vDS when it comes to moing VMkernel ports than the vSS in powershell, we can add one VMKernel port at a time. We get the port group object from the vDS and the VMkernel port we wish to move and then migrate it using the Set-VMhostNetworkAdapter cmdlet.

$vmk1pgObj = Get-VDPortgroup -name $vmk1pg -VDSwitch $vdsObj
$vmk1 = Get-VMHostNetworkAdapter -Name vmk1 -VMHost $vmhost
Set-VMHostNetworkAdapter -PortGroup $vmk1pgObj -VirtualNic $vmk1 -confirm:$false | Out-Null

We repeat this for each VMKernel port and prompt to continue between each one, so that we can validate that everytihng is ok. Now, this could be put into a for loop to go through each adapter, but it was easier to do it this way (not necessarily better).

Once all the VMKernel ports have moved over, we can now move the VM networking back to the vDS. This is done muc the same way as we did before, although we are using the -Distributed switch in the Get-VirtualPortGroup cmdlet.

$VMhostObj = Get-VMhost $VMhost
$VMlist = $VMhostObj | get-VM
Write-Host "Now migrating VM networks from $vss to $vds" -ForegroundColor Yellow
foreach ($VM in $VMlist){
$VMnic = Get-NetworkAdapter $vm
$VMnic | Set-NetworkAdapter -PortGroup (Get-VirtualPortGroup -VMhost  $VMHost -Distributed -Name
$vmnic.NetworkName) -Confirm:$false | out-null
Write-Host "Migrated $VM network to vSS on $VMhost" -ForegroundColor Cyan
}

Note that we had to get the $VMlist again as the vm object ids are now difference since we have changed vCenter servers.

Next we swing the last adapter over to the vDS:

$pNIC2Obj = Get-VMHostNetworkAdapter -VMhost $vmhost -Physical -name $pNIC2
$vdsObj | Add-VDSwitchPhysicalNetworkAdapter -VMHostNetworkAdapter $pNIC2Obj -Confirm:$false

If all went well, we can move onto putting the virtual machines into their correct folder location, thanks to the functions we touched on earlier, it’s an easy one liner:

$VMfolders | Move-VMtoFolderPath

Now all we need to do is cleanup after ourselves and delete the vSS off the host:

$vssObj = Get-VirtualSwitch -VMhost $VMhost -Name $vss
Remove-VirtualSwitch $vssObj -confirm:$False

This is probably not the most efficient code to do these steps, it can easily be modified to loop through each host in a cluster, or even a vCenter server, however that could also spell disaster. Use it at your own risk with your own discretion. It definitely beats doing it manually. Oh yeah, don’t forget to let your backup team and resolver groups know that the VMs have moved to a new vCenter.

I hope this helps you with your migrations and has been a bit informative, as opposed to just giving you a script to execute.

Schedule Automatic VCSA Backups

Whilist evaluating the backup and restore methods for a 6.5 deployment, I came across the PowerShell functions Brian Graf put together to backup perform a file based backup of the VCSA via the new VAMI RESTful API. Thanks Brian!

Grab the script here: https://github.com/vmware/PowerCLI-Example-Scripts/tree/master/Modules/Backup-VCSA

After some initial testing in the lab, the script worked a treat. Logically for me the next step was to schedule the script to run from a management server. If you’ve seen the script, you would ahve noticed that the password needs to be stored in a variable, as a specifc format as Brian had called out. For me this wasn’t going to work, the secuirty folk would have beat me across the head if I had passwords written in plain text within the script. Having used the New-VICredentialStoreItem command in the past to save the credentials, I figured there should be a way to do something similar with the password variables in the script. After some google-fu, here is what I put together to get it working.

Firstly, we need to setup a couple things before running the script:

The script requires you to authenticate against the VAMI for the VCSA (or the PSC) using the SSO domain credentails, so saving these credentials is first. Luckily enough there is a PowerCLI commandlet that will do this for us. It is as simple as below:

Connect-CisServer 10.1.1.120 -User "administrator@vsphere.local" -Password "bla" -SaveCredentials

The important thing to note here is that this should be run in the context of the account that you wish to run the scheduled task under.

Next we need to create two encrypted files containing the passwords, one for the backup encryption password and the other for the backup target. This can be done with the below command:

“YourSuperSecretPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\ScriptsBackupVCSA.vma” 

Ok, so we have our encrypted passwords. As mentioned before, we now need to pull these into variables in the script so that we can make utilize Brian’s backup function.

For the backup target location, I am using the vMA I had available in the environment. Here is how we pull in that credential into a variable.

$getVmaPass = Get-Content “D:ScriptsBackupVCSA.vma”

Next we need to convert the varaible to a secure string format:

$SecurePassword = ConvertTo-SecureString $getVmaPass

Now we decrypt it into plain text:

$BSTR =[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$LocationPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Now if you run $LocationPassword in your PowerCLI session, you will see your password stored as a string. Now as Brian calls out, the API needs it in a particular format, which is “VMware.VimAutomation.Cis.Core.Types.V1.Secret”.

I have just added Out-Null to the end of the line so that the password is not spat into the PowerCLI output / transcript.
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$LocationPassword ” Out-Null
Now we just repeat the same script, but changing the variables to pull in the backup encruption password:

$getBackupPass = Get-Content "D:ScriptsBackupVCSA.bu"
$SecurePassword = ConvertTo-SecureString $getBackupPass
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$BackupPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword | Out-Null

We now have our two variables that we can now pass through to make our API call. Please note that this wont stop anyone from who knows what theyre doing to decrpt the files, however its better than keeping the variables in plain text.

Below is the entire script all put together which you can place into a scheduled task. You can use this on an external PSC also, you just need to change he backup type from -FullBackup to -CommonBackup.

<#
.SYNOPSIS

  Perform Backup of the VMware Vitual Center Server Appliance

.DESCRIPTION

  Performs a file based backup of the VCSA or External PSC
  This script utilizes the Backup-VCSA module found here:
  https://github.com/vmware/PowerCLI-Example-Scripts/tree/master/Modules/Backup-VCSA

Assumptions:
  BackupVCSA module has been placed in the appropriate modules directory
  SSO Credentials for the appliance have been saved in the context of the acccount that is running the script:
  "Connect-CisServer 10.1.1.120  -User "administrator@vsphere.local" -Password "bla" -SaveCredentials"
  Passwords for backup and appliance have been stored as secure string to file using:
  "secret" " ConvertTo-SecureString -AsPlainText -Force  ConvertFrom-SecureString " Out-File "D:\some\dir\secret.file"

.PARAMETER none
.INPUTS none
.OUTPUTS

  Backup files will be stored on the vMA:
  vma01:/workspace/backups/vcsa/vcsa-yyyy-MM-dd-hh-mm

.NOTES

  Version:        1.0

  Author:        vKARPS

  Creation Date:  26/10/17

.EXAMPLE

  ./BackupVCSA_prd.ps1

#>

#Start Transcript
Start-Transcript -path  D:\Scripts\BackupVCSA_prd.log -Force

#Connect to VAMI on VCSA
Connect-CisServer 10.1.1.120

#Get credential for vMA
$getVmaPass = Get-Content "D:\Scripts\BackupVCSA_prd.vma"
$SecurePassword = ConvertTo-SecureString $getVmaPass
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$LocationPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$LocationPassword | Out-Null

#Get Credential for Backup
$getBackupPass = Get-Content "D:\Scripts\BackupVCSA_prd.bu"
$SecurePassword = ConvertTo-SecureString $getBackupPass
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$BackupPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword | Out-Null

#Set Comment for the backup
$Comment = "VCSA Backup $((Get-Date).ToString('yyyy-MM-dd-hh-mm'))"

#Setup Backup Target
$LocationType = "SCP"
$location = "10.1.1.100/workspace/backups/vcsa/vcsa-$((Get-Date).ToString('yyyy-MM-dd-hh-mm'))"
$LocationUser = "vi-admin"

#Initiate backup -CommonBackup is configuration only as PSC does not contain performance statistics
Backup-VCSAToFile -BackupPassword $BackupPassword -LocationType $LocationType -Location $location -LocationUser $LocationUser -LocationPassword $LocationPassword -Comment $Comment -ShowProgress -FullBackup

#Set variables to 0
$getVmaPass, $getBackupPass,$SecurePassword,$BSTR,$BackupPassword,$LocationPassword,$LocationType,$location,$LocationUser,$Comment = 0

#Disconnect from VAMI
Disconnect-cisserver -confirm:$false
Stop-Transcript

Ive noticed a little bug with the editor I am using, the ” (pipe) between commandlets it being switched to a ” in the code. I will look at fixing this later in the week. I should really get around to setting up a GitHub account hey…

If youre reading this and cringing and know a better way (especially in storing the passwords), please get in touch as I would be keen to learn something from you.

Anyway, hope you find this helpful.

PowerCLI not connecting to vCenter in another domain

I came across an odd issue the other day where my PowerCli session would not authenticate to a vCenter in another domain within the forest, although I could get to the one on my local domain. Here’s the error I was getting:

[Connect-viserver vcsa02.deathstar.local
Connect-viserver : 13/10/2017 10:17:35 AM Connect-VIServer Could not resolve the requested VC server.
Additional Information: There was no endpoint listening at https://vcsa02.deathstar.local/sdk that could accept the
message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
At line:1 char:1
+ Connect-viserver vcsa02.deathstar.local
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Connect-VIServer], ViServerConnectionException
+ FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_NameResolutionFailure,VMware.VimAutomation.ViCo
re.Cmdlets.Commands.ConnectVIServer

Some head banging ensued after ruling out the regular DNS and vCenter service functionality, I soon realised that I could connect via another workstation so I knew it was something with the workstation PowerShell instance.

Turns out, I forgot that the day before I was playing with the powershell proxy settings so that I could get out to the interwebz and update to the latest PowerCLI release.

Get-PowerCLIConfiguration returned ‘UseSystemProxy’:

[10:55:38]# get-powercliconfiguration

Scope ProxyPolicy DefaultVIServerMode InvalidCertificateAction DisplayDeprecationWarnings W
----- ----------- ------------------- ------------------------ -------------------------- -
Session UseSystemProxy Multiple Unset True -
User Multiple
AllUsers NoProxy

After setting the proxy configuration to ‘no proxy’ in PowerShell with the below command I was able to connect again.
Set-PowerCliConfiguration -proxypolicy noproxy

Updating php 7.0 to php 7.1 Ubuntu 16.04

Disclaimer: I come from a Windows background, my expertise in linux is quite slim.

In my home lab I had a requirement to update a software package which dropped support for php 7.0, which meant I needed to upgrade to 7.1 prior to upgrading the application.

Here are the steps that worked for me:

First stop the web server, in my case apache.

sudo service apache2 stop

Get a list of the current php packages you are using

dpkg -l | grep php

Add the repo, install the base packages, followed by the extra ones you were using with 7.0 ( my packages may differ from yours)

sudo add-apt-repository ppa:ondrej/php

sudo apt-get install php7.1 php7.1-common
sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-curl php7.1-mcrypt php7.1-json php7.1-mbstring php7.1-bcmath php7.1-zip php7.1-intl php7.1-opcache php7.1-readline

Reconfigure apache2 for php 7.1 and restart the service

sudo a2enmod php7.1

sudo service apache2 restart

check that php 7.1 is now running

php -v

PHP 7.1.8-2+ubuntu16.04.1+deb.sury.org+4 (cli) (built: Aug 4 2017 13:04:12) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.1.8-2+ubuntu16.04.1+deb.sury.org+4, Copyright (c) 1999-2017, by Zend Technologies

remove your old 7.0 packages

sudo apt purge php7.0-cl php7.0-bcmath php7.0-common php7.0-curl php7.0-intl php7.0-json php7.0-mbstring php7.0-mcrypt php7.0-mysql php7.0-opcache php7.0-readline php7.0-zip

vSphere Replication ‘Solution user detail’ certificate is invalid

I came across an odd ball today when upgrading a customers vSphere Replication appliance from 5.8.1 to 6.0. For those who have done a VR in place upgrade before, you will know that there is really not much to it; Mount ISO, Install Update, Reboot, done. When VR 6.0 was introduced an additional step is required after you perform the upgrade, you had to go in and register it with your lookup service. All this requires is the lookup service url and the SSO administrator credentials and you’re done as per the documentation here.

Instead I was presented with this error message:

'Solution user detail' certificate is invalid - certificateException java.security.cert.CertificateExpiredException: NotAfter: Fri Jun 17 23:01:55 UTC 2016

img-alternative-text

Its probably worth noting that this has come off the back of a vCenter upgrade to 6.5, so ‘solution user’ automatically got me looking at SSO solution users in the web client and the vCenter extension manager to validate that the certificate thumbprints matched up.

Sure enough, the thumbprint that was registered with vCenter matched the one of the vSphere Replication appliance. My google-fu didnt get me any furhter either, next thing that came to mind was ssh and logs. I saw the secuiry tab and figured I would enable ssh from there…nope, no enable ssh option there dummy. What I did see on the secuirty tab was this.

Right, expity date matches the error message!

So here is what you need to do:

Head back over on the configuration page there is a “Install a new SSL Certificate” section where you can generate and install a self signed or your own certificate.

Hit the Generate and Install button, validate the warning that it will overwrite the existing one and let it do its thing.

img-alternative-text

 

Once it is done, you will be prompted by the following message.

img-alternative-text

Reload your brower like it states, even though it seems as if does it when it takes you do the login page.

Once you’re back in, populate your Lookup Service URL and SSO Administrator credentials at the configuration tab and hit Save and Restart service. If all went well, you should get the below message.

img-alternative-text