How to Backup or Recover SPBM with PowerCLI

We have discussed about the SPBM  and how to create SPBM on previous posts , today we are going to discuss about how can backup and restore the SPBM from Power CLI  .

Why we need backup or restore operation on SPBM 

Just imagine once the case we have to redeploy our vCenter which is coiffured with vSAN  and there are many policy . In such cases power CLI is the best tool to perform backup and restore of SPBM .

You can use below commands to perform required tasks

Check the Available Policy 

# Get-SpbmStoragePolicy

I  have created and using two policies on my vSAN environment New Test Policy and New ISCSI Test Policy

# Get-SpbmStoragePolicy -Name "Policy Name"

Check the Policy Detail with specific name which we provide

# Get-SpbmStoragePolicy  | Format-List

Get the Options available with Get-SpbmStoragePolicy Command

#Get-SpbmStoragePolicy -Id "PolicyId"

Listing policy with policy ID which we found from above command

#Get-SpbmStoragePolicy -Requirement -Namespace "VSAN"

Returns all storage policies of type Requirement containing one or more rules which contain one or more capabilities from the "VSAN" namespace

Export the Policy 

# Export-SpbmStoragePolicy -StoragePolicy $policy -FilePath 'folder\file path'

Exported File Looks like below

Exports a storage policy to the policy.xml file in location . If a file with the same name already exists in this location, the file is overwritten. And if you do not use the Force parameter, the command returns an error about the existing file.

Import Policy 

#Import-SpbmStoragePolicy -Name "Policy Name" -Description "PolicyDescription" -FilePath C:\policy.xml

Imports a storage policy with your name " Policy Name" and description "PolicyDescription" from the policy.xml file to a server. 
And new storage policy is created on the server.

Export All Policy

If you want to export all the policy to specific folder  , you can follow below power shell script .


# Get a list of all the storage policies on the specified vCenter Server
$StoragePolicies = Get-SpbmStoragePolicy

# Enumerate the list of storage policies
Foreach($StoragePolicy in $StoragePolicies) {

# Get the name of the policy that is being exported.
$PolicyName = $StoragePolicy.Name

Export-SpbmStoragePolicy -FilePath C:\Users\Administrator\Desktop\POLICY\ -StoragePolicy $StoragePolicy.Name
}


Note :- This Script will work only for after connecting to vCenter from power CLI else you have add commands to connecting to vCenter to this script .

Reference

Script for export and import can be found on the VMware Developer Site


Collect vSwicth Information Using vSphere Power CLI

In this  Post  sharing the Script to collect the Virtual Standard Switch Information from vSPhere power cli to CSV file .

You can Modify  the Location of the file to save and directly apply to vSPhere Cli Window or  you can save this as .PS1  extension and run  CLI window .

Script 


&{foreach($esx in Get-VMHost){
$vNicTab = @{}
$esx.ExtensionData.Config.Network.Vnic | %{
$vNicTab.Add($_.Portgroup,$_)
}
foreach($vsw in (Get-VirtualSwitch -VMHost $esx)){
foreach($pg in (Get-VirtualPortGroup -VirtualSwitch $vsw)){
Select -InputObject $pg -Property @{N="ESX";E={$esx.name}},
@{N="vSwitch";E={$vsw.Name}},
@{N="Active NIC";E={[string]::Join(',',$vsw.ExtensionData.Spec.Policy.NicTeaming.NicOrder.ActiveNic)}},
@{N="Standby NIC";E={[string]::Join(',',$vsw.ExtensionData.Spec.Policy.NicTeaming.NicOrder.StandbyNic)}},
@{N="Portgroup";E={$pg.Name}},
@{N="VLAN";E={$pg.VLanId}},
@{N="Device";E={if($vNicTab.ContainsKey($pg.Name)){$vNicTab[$pg.Name].Device}}},
@{N="IP";E={if($vNicTab.ContainsKey($pg.Name)){$vNicTab[$pg.Name].Spec.Ip.IpAddress}}}
}
}
}} | Export-Csv C:\vswitch.csv -NoTypeInformation -UseCulture


Result 

Result of the script will shown like below .

ESX vSwitch Active NIC Standby NIC Portgroup VLAN Device IP
ESX-TEST-01 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 Management Network 101 vmk0 192.168.1.11
ESX-TEST-01 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_114 114
ESX-TEST-01 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_131 131
ESX-TEST-01 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_132 132
ESX-TEST-01 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_133 133
ESX-TEST-02 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 Management Network 101 vmk0 192.168.1.12
ESX-TEST-02 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_114 114
ESX-TEST-02 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_131 131
ESX-TEST-02 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_132 132
ESX-TEST-02 vSwitch0 vmnic0,vmnic1,vmnic2,vmnic3 VLAN_133 133

Virtual Network Management in Standard Switch Using Power CLI

This Post will help you to understand and create multiple port groups , Esxi host network details for complete environment  .
Note : Below  commands are used on vCenter with One host , it can be used multiple servers environment .
List vSwitch Inventory 
Get-VirtualSwitch
List Portgroup Inventory 
Get-VirtualPortGroup

Create a Virtual Switch

Get-VmHost | New-VirtualSwitch -Name "Test"

Create and add PortGroup to all ESXi hosts in cluster

Get-Cluster “clustername” | Get-VMHost | Get-VirtualSwitch -Name “vSwitch0” | New-VirtualPortGroup -Name “Portgrounp Name” -VLanId "XX"

Get VM host network details and output to the PowerCLI console:
Get-VMHostNetworkAdapter | select VMhost, Name, IP, SubnetMask, Mac, PortGroupName, vMotionEnabled, mtu, FullDuplex, BitRatePerSec
Get VM host network details to CSV
Get-VMHostNetworkAdapter | select VMhost, Name, IP, SubnetMask, Mac, PortGroupName, vMotionEnabled, mtu, FullDuplex, BitRatePerSec | Export-Csv C:\VMHostNetworkDetails.csv

Output

List of MAC addresses for all VMs on vcenter or Esxi and export to CSV

Get-View -Viewtype VirtualMachine -Property Name, Config.Hardware.Device |`Select name,@{n="MAC(s)"; e={($_.Config.Hardware.Device |
?{($_ -is [VMware.Vim.VirtualEthernetCard])} | %{$_.MacAddress}) -join ","}} | `Export-Csv c:\temp\VMMACsInfo.csv -UseCulture -NoTypeInformation

Note: You can directly use all commands in Power CLI or save file as Script with .PS1 extension run .

Output


Find Number of VCPU used in a Cluster and ESXi hosts

This Post explain how can we generate an output contains , Total number of vCpu used in an vCenter Cluster , also it shows many vCPU used per Esxi hosts .  If you have  multiple Cluster it is very easy to find same using below script.

Connect-VIServer  "vCenter Name"

$TotalNumvCPUs = 0
Foreach ($Cluster in (Get-Cluster |Sort Name)){
$HostNumvCPUs = 0
Write-Host “Cluster: $($Cluster.name)“
Foreach ($ESXHost in ($Cluster |Get-VMHost |Sort Name)){
Write-Host “ Host: $($ESXHost.name)“
$RunningLimit = $null
$RunningLimit = ($ESXHost |Get-VMHostAdvancedConfiguration).get_Item(“Misc.RunningVCpuLimit“)
If ($RunningLimit -eq $null){
$RunningLimit = 128
}
Write-Host “ Misc.RunningVCpuLimit: $RunningLimit“
Foreach ($VM in ($ESXHost |Get-VM)){
$HostNumvCPUs += ($VM).NumCpu
}
Write-Host “ Number of vCPU on host: $($HostNumvCPUs)“
$TotalNumvCPUs += $HostNumvCPUs
$HostNumvCPUs = 0
}
Write-Host “———-“
Write-Host “Number of vCPU in $($Cluster.name): $TotalNumvCPUs“
Write-Host “———-“
Write-Host “”
$TotalNumvCPUs = 0
}

Output 

 

 


NTP Conflagration with Power CLI

Check NTP Services status 

Get-VMHost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"}

 

 

 

 

 

 

 

 

Check Firewall exception configuration 

Get-VMHost | Get-VMHostFirewallException | where {$_.Name -eq "NTP client"}

 

 

 

 

 

 

 

Enable the FirewallException to all ESXi Hosts

Get-VMHost | Get-VMHostFirewallException | where {$_.Name -eq "NTP client"} |Set-VMHostFirewallException -Enabled:$true

Disable the FirewallException to all ESXi Hosts

Get-VMHost | Get-VMHostFirewallException | where {$_.Name -eq "NTP client"} |Set-VMHostFirewallException -Enabled:$false

Start the NTP service on all ESXi nodes

Get-VMHost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService

Stop the NTP service on all ESXi nodes

Get-VMHost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Stop-VMHostService   ( use  " -Confirm:$false to avaoid the the popoup quetion abut confimration )

 

 

 

 

 

 

 

Add the NTP servers to all ESXI Hosts

Get-VMHost | Add-VMHostNtpServer 192.168.1.1o,192.168.1.11

 

 

 

 

Verify NTP servers added  by running below command

Get-vmhost esx1.test.com |Get-VMHostNtpServer

 

 

 

 

Remove the NTP servers from ESXi Hots 

Get-vmhost esx1.test.com |Remove-VMHostNtpServer 192.168.1.10,192,168,1,11  -confirm:$false

 

 

 

Check the NTP Policy Configured 

Get-VMhost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"}

 

 

 

 

 

 

Configure the  NTP Policy 

 

Get-VMhost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Set-VMHostService -policy "automatic"

Note:- Get-VMhost "ESXIHOSTNAME" , if you use this you can apply these setting only to that HOST

             It is recommended to set the time manually prior to starting the service.


CBT Management with Power CLI

List all virtual machines where CBT enabled 

Get-VM| Where-Object{$_.ExtensionData.Config.ChangeTrackingEnabled -eq $true}

Check specific virtual machines where CBT enabled 

Get-VM  "TEST-VM-01" | Where-Object{$_.ExtensionData.Config.ChangeTrackingEnabled -eq $true}

List all virtuals machine where CBT disabled

Get-VM| Where-Object{$_.ExtensionData.Config.ChangeTrackingEnabled -eq $false}

Check specific virtual machines where CBT disabled

Get-VM  "TEST-VM-01" | Where-Object{$_.ExtensionData.Config.ChangeTrackingEnabled -eq $false}

Note : In GUI mode we cannot modify the CBT configuration while virtual machine is powered on , so we can use below script to enable or disable CBT in VM powered on state.

Script to enable CBT

$vmtest = Get-VM TEST-VM-01 | get-view
$vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfigSpec.changeTrackingEnabled = $true
$vmtest.reconfigVM($vmConfigSpec)

Script to disable CBT

$vmtest = Get-VM TEST-VM-01 | get-view
$vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfigSpec.changeTrackingEnabled = $disabale
$vmtest.reconfigVM($vmConfigSpec)

You may use the above commands by pasting on vSphere CLI after connecting to vCenter   or  save it as .PS1  extension and run from the directory

Reference


Snapshot Management with Power CLI

Command to list the  properties of snapshot  using  power cli

get-vm | get-snapshot | format-list

Description
Created
Quiesced
PowerState
VM
VMId
Parent
ParentSnapshotId
ParentSnapshot
Children
SizeMB
IsCurrent
IsReplaySupported
ExtensionData
Id
Name
Uid

Generate complete snapshot inventory with few details

       get-vm | Get-Snapshot

Export complete snapshot inventory to csv file

get-vm | get-snapshot | format-list | Export-Csv C:\snaps.csv

Generate snapshot information inside folder  

   get-vm -location “VMWARE-Administration” | get-snapshot

Generate snapshot information with specific Description

get-vm | get-snapshot  | where {$_.Description -match "Avamar Snapshot generated for back" }    ->

Generate snapshot information with specific Description and formatted mode

get-vm | get-snapshot  | where {$_.Description -match "Avamar Snapshot generated for back"}| Format-Table -Property VM,Name,Created,Description, SizeMB


Create new snapshot with description and name

get-vm TEST-VM-01 |New-Snapshot -name snspshottest -Description  snapshottest

Get snapshot information about specific VM      

get-vm TEST-VM-01 | Get-Snapshot

Remove snapshot of a specific VM

get-vm TEST-VM-01 |Get-Snapshot |Remove-Snapshot    ( It will ask to confirm to perform snapshot removal )

get-vm TEST-VM-01 |Get-Snapshot |Remove-Snapshot  -Confirm:$false


Remove Snapshot By Description

get-vm | get-snapshot  | where {$_.Description -match "Avamar Snapshot generated for back"}| Remove-Snapshot -Confirm:$false -RunAsync

List snapshot created prior to "X" days

Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-130)}
Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-60)}

Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-60)} | Select-Object VM, Name, Created, SizeMB

Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(1)} | Select-Object VM, Name, Created, SizeMB


Power CLI Command to List Connected Disks to ESXi Hosts

Get connected disk details including name , Multipathing , LunType  of all ESXI HOSTS in vCenter

Get-VMHost | Get-ScsiLun -LunType disk

User below command to export all the details to CSV

Get-VMHost | Get-ScsiLun -LunType disk |export-csv C:\diskinfo.csv

Get connected disk details including name , Multipathing , LunType  for Specific ESXI HOST

Get-VMHost  "ESXI-TEST.LOCAL.COM" | Get-ScsiLun -LunType disk

 


Script to List Virtual Machine HW ,VM Tools Version , Tools Status

Below Script will get  virtualmachine hardware version , tools version , Tools status , Tools version status .

Connect-VIServer -Server VM-VC.TEST.COM  -User  root -Password ********

Get-VM |

Select @{N="VMName"; E={$_.Name}},

@{N="HardwareVersion"; E={$_.Extensiondata.Config.Version}},

@{N="ToolsVersion"; E={$_.Extensiondata.Config.Tools.ToolsVersion}},

@{N="ToolsStatus"; E={$_.Extensiondata.Summary.Guest.ToolsStatus}},

@{N="ToolsVersionStatus"; E={$_.Extensiondata.Summary.Guest.ToolsVersionStatus}},

@{N="ToolsRunningStatus"; E={$_.Extensiondata.Summary.Guest.ToolsRunningStatus}}

| Export-Csv  C:\vmdata.csv

Output 

VMName HardwareVersion ToolsVersion ToolsStatus ToolsVersionStatus ToolsRunningStatus
TEST-VM-01 vmx-11 10249 toolsOld guestToolsNeedUpgrade guestToolsRunning
TEST-VM-01 vmx-11 2147483647 toolsOk guestToolsUnmanaged guestToolsRunning
TEST-VM-01 vmx-11 10282 toolsOk guestToolsCurrent guestToolsRunning
TEST-VM-01 vmx-11 10249 toolsOld guestToolsNeedUpgrade guestToolsRunning
TEST-VM-01 vmx-08 2147483647 toolsOk guestToolsUnmanaged guestToolsRunning
TEST-VM-01 vmx-11 10249 toolsNotRunning guestToolsNeedUpgrade guestToolsNotRunning
TEST-VM-01 vmx-10 9354 toolsOld guestToolsNeedUpgrade guestToolsRunning

Script For Datastore Utilization

Script For Datastore Utilization

This script is very useful to generate the Datastore Utilization of  VMware Infra

Save the below script as .PS1 extension  and Run fron vSphere Power CLI ,  Out Put will be saved on  the Location where we mention  , here it is c:\datstoreusage.csv

Connect-VIServer (MyvCenter) -User (My Username)-Password (My Password)

Get-Datastore |

Select Name,

@{N='Type';E={"$($_.Type)$($_.ExtensionData.Info.Vmfs.MajorVersion)"}},

@{N='CapacityGB';E={[math]::Round($_.CapacityGB)}},

@{N='FreeSpaceGB';E={[math]::Round($_.FreeSpaceGB)}},

@{N='UsedSpaceGB';E={[math]::Round($_.CapacityGB - $_.FreeSpaceGB,1)}},

@{N='% of LUN Utilization';E={[math]::Round(($_.CapacityGB - $_.FreeSpaceGB)/$_.CapacityGB * 100,1)}} |

Export-Csv   c:\datstoreusage.csv  -NoTypeInformation -UseCulture