PowerCLI Scripting For VMware VSphere
PowerCLI Scripting For VMware VSphere
The esxcli command exposes a number of namespaces against which you can run queries to retrieve information about
ESXi as well as configure it. The following table lists the available namespaces on ESXi 6.5 along with a description for
each (source: VMware). For earlier ESXi releases, consult the relevant online documentation or run esxcli with no
parameters to see which namespaces are available.
Command Description
esxcli device Lists descriptions of device commands.
esxcli elxnet Lists descriptions for commands that manage Emulex elxnet drivers.
esxcli esxcli Lists descriptions of esxcli commands.
esxcli fcoe FCOE (Fibre Channel over Ethernet) commands
esxcli Graphics commands
graphics
esxcli Hardware namespace. Used primarily for extracting information about the current system setup.
hardware
esxcli iscsi iSCSI namespace for monitoring and managing hardware and software iSCSI.
esxcli Network namespace for managing virtual networking including virtual switches and VMkernel network
network interfaces.
esxcli nvme Commands for managing NVMe devices.
esxcli rdma Commands for monitoring RDMA devices.
esxcli sched Manage the shared system-wide swap space.
esxcli Software namespace. Includes commands for managing and installing image profiles and VIBs.
software
esxcli storage Includes core storage commands and other storage management commands.
esxcli system System monitoring and management command.
esxcli vm Namespace for listing virtual machines and shutting them down forcefully.
esxcli vsan Namespace for Virtual SAN management commands. See the vSphere Storage publication for details.
The following is a compilation of esxcli commands, sorted by namespace, I tend to use on a regular basis. It is by no
means exhaustive as there are too many examples to mention. If you want the whole shebang, have a look at VMware’s
documentation site.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Description: Returns the hostname, domain and FQDN for the host.
Description: Returns the date and time of when ESXi was installed.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Description: This command allows you to create local ESXi users. All the parameters used in the example are
mandatory.
Description: Use this command to put ESXi in maintenance mode or take it out.
Description: Use this command to reboot or shutdown ESXi. The -d parameter is a countdown timer; minimum 10
seconds. ESXi must be in maintenance mode before you can use the command.
Description: Returns the status of the ESXi firewall. The default action is to drop traffic unless allowed through by a
specific firewall rule. The Enabled field indicates whether the firewall is enabled. The Loaded field shows whether the
firewall module is active or not (see esxcli firewall load | unload commands).
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Description: Use this command to disable the ESXi firewall for troubleshooting purposes. Note that disabling the
firewall on ESXi is highly discouraged.
Description: Generates a list of all enabled firewall rules on ESXi. The command is piped to awk which will matches
the value from the second column to “true” so only enabled rules are displayed.
Description: Displays the IPv4 configuration for all the interfaces present on ESXi.
Description: Lists all the currently installed VIBs on ESXi. A VIB is a file packaging format used to distribute software
on ESXi.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Description: Use this command to update an installed VIB on ESXi. Note that the command does not install any new
software. Instead it only updates what’s currently installed. Use esxcli software vib install instead when installing new
software. The -d parameter specifies the full path to the package being used for the update. As per the next screenshot, I
specified a non-existing patch hence the error message.
Description: Lists all the running VMs on the hosts. The World ID can be used with other commands to carry out
various tasks related to VMs.
Description: Use this command to kill a running VM such as one that fails to respond to commands. You must first
retrieve the VM’s World ID (see command #14) and pass it on using the -w parameter. The -t <soft | hard |
force> mandatory parameter sets the type of kill operation. Start with soft so you allow the VM to shut down cleanly. If
this does not work, try the hard option which will kill the VM processes immediately as in kill -9. The Force type
should only be used as a last resort. If none work, your only option is to reboot ESXi.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Description: The command generates a list of extents for each volume as well as the corresponding device name to
UUID mapping.
Description: The command lists of all the volumes or datastores accessible by the ESXi host. The output includes the
file system type, disk info along with the volume name, path and UUID.
#18: esxcli iscsi software set –enabled true && esxcli iscsi software get
Description: The above command actually consists of two concatenated commands, which is what && does. The first
command enables the iSCSI software adapter and the second verifies that the iSCSI adapter is enabled.
Description: The command returns metrics for the specified iSCSI adapter. These include the current, minimum and
maximum values and whether the listed parameters may be configured or not. The name of the iSCSI adapter you want
to be queried is specified via the -A parameter. The adapter name is retrieved using esxcli iscsi adapter list or from the
vSphere Web client.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Previously, we looked at PowerCLI – what it is, how to install it, and integrating into Windows Powershell ISE. Now,
let’s take a look at basic scripting including connecting, PowerCLI commandlets, as well as looping.
Let’s take a look at a few basic PowerCLI commandlets to see how easy it is to start pulling information from our
vSphere environment with PowerCLI. Keep in mind, the below is in no way meant to be an all-encompassing tutorial,
but rather an introduction to PowerCLI and how to get started running commandlets and learning to automate your
environment.
The first commandlet we need to run is the one to actually connect to our vSphere environment. You can either connect
directly to an ESXi host or to vCenter Server.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
connect-viserver –server 〈yourserver〉
When you run the command, you will be prompted for your login credentials. Type in your username and password for
either your ESXi server or vCenter Server.
One of the most basic commands we can run when we connect to either ESXi or vCenter is seeing all the VMs in the
environment. We use the get-vm commandlet to show information about the guest VMs.
Get-VM – The get-vm commandlet lists VMs running on the connected host
To get more verbose information from the get-vm commandlet, we can show the full information with the command:
Get-VM | fl – Displays more verbose information such as the Guest Operating System, Resource pools, VM
Hardware version level, folder it is located in, and many other details.
Now, let’s return specific useful information from the Get-VM commandlet. Let’s find the VMs that are in the
PoweredOff state. We can get information from the Get-VM commandlet and then pipe that into where-object to select
out the specific information we want to query for – in this case PowerState. As you can see, there are worlds of
possibilities in getting various VM information and piping this information into another PowerShell commandlet.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
As you can see, this displays only the VMs that are in the “PoweredOff” PowerState. This can be extremely useful. We
can even pipe the result of the above command into the Start-VMcommandlet. So essentially we can get all the
powered off VMs and then power those VMs on.
What about shutting down specific VMs? We can do that as well. We can call the VM by name and then use the Stop-
VMGuest commandlet which initiates a guest operating system shutdown.
If you do not want to receive the confirmation of the action, we can add the –confirm:falseparameter:
Let’s say we want to see how many VMs we have running that have more than 1 CPU assigned. Again, we can use
the where-object commandlet to select out the NumCpu object.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
PowerCLI Loops
Loops allow you to perform the same operation multiple times against either selected objects or for a number of times
looped through. For instance, with a foreach loop, we can loop a certain action multiple times. It is setup like the pseudo
code below:
If we want to get specific about which objects we are going to perform the action on, we can, for example, loop through
a specific list of VMs from a text file. To populate the text file, we can run our Get-VM commandlet selecting out the
properties we want, then pipe that to a text file. We can then use PowerShell to read the text file and place the VMs into
an array on which we can loop through and perform an action. Below we are adding a new network adapter to VMs in
the list.
The reason virtual infrastructures are put together is primarily (and unsurprisingly) to run virtual machines, so a good
place to start is with the Get-VM cmdlet, which can produce a simple inventory of all VMs currently found within
VMware vCenter . Using the Get-VM cmdlet, and the standard PowerShell Select-Object cmdlet, you can retrieve the
particular properties that are of interest and use Export-CSV to export that data into the ever-useful CSV file format for
further manipulation and distribution.
Another example where this cmdlet can be put to good use is to alleviate a common stumbling block when attempting to
VMotion virtual machines from one ESX host to another (in case you don’t use VMware regularly, “to VMotion virtual
machines…” means “to use VMware VMotion to Live Migrate virtual machines to another physical host…”). There are
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
a number of reasons why a virtual machine might not be permitted to VMotion; one of the most common is because it
has a local CD-Rom drive attached. The below set of commands will iterate through all virtual machines, filter them
based on whether the connection state of their CD-Rom drive is true, and return the name of the offending virtual
machine(s):
One of the great things about PowerShell is the intuitive possibility to gradually build up a set of commands to carry out
increasingly more complex actions. This means it becomes possible to both review and appropriately configure your
VMs in a single step. In this instance, as well as retrieving the list of virtual machines where the CD-Rom is connected,
it is very simple to extend the above command to automatically disconnect these CD-Roms, rather than carry out that
task manually. Simply use the Set-CDDrive cmdlet to change the connection status of any connected CD-Roms which
have been found:
This is just a single example, but now that you know how to quickly gather the data you need, you can easily target
specific settings and make appropriate configurations a snap. You can find out more about what cmdlets are available to
adjust your VMs’ settings from the PowerCLI website, as mentioned earlier.
The PowerCLI cmdlets can be used to give a quick overview of the number of hosts and VMs that exist within the
Virtual Center; it could be useful to record these figures on a monthly basis so that the growth of the environment can be
tracked over time. How about finding the average number of VMs per host in a cluster? Again, a useful figure to
regularly record so as to observe what consolidation ratios are being achieved and to plan for future capacity needs, and
a figure which PowerCLI can help you find.
In the code below, we retrieve the ESX / ESXi hosts & VMs and observe their count; note the use of
the $DefaultVIServer variable, which is updated each time a connection is made to a vCenter.
For the average number of VMs in each cluster, we find the total number of ESX / ESXi hosts and VMs and perform
some basic maths to arrive at a figure. Note the use of some basic .NET [math]::round code and the number of decimal
places (1) required to format the output as desired:
$TotalVMHosts = (Get-VMHost).Count
$TotalVMs = (Get-VM).Count
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Write-Host "There are $TotalVMs Virtual Machines in $DefaultVIServer"
$Clusters = Get-Cluster
What used to be one of the most onerous tasks for a VMware administrator was using the vSphere Client GUI to re-scan
all hosts in a cluster for new storage after an additional SAN Lun had been provisioned. This would require individually
selecting each host within the cluster, scanning it for new storage, and then moving on to the next host until all were
complete – a process which quickly becomes frustrating.
Thankfully, in vSphere 4.0, VMware added a new option when right-clicking a cluster – Rescan for Datastores. Once
initiated, this task would work through each host in the cluster and scan for new storage.
However, if you are running a VMware version prior to version 4.0 in your environment, or maybe you want to rescan
hosts in more than one cluster, then the Get-VMHostStorage cmdlet has two parameters which you’ll find useful: -
RescanAllHba and -RescanVmfs. Used in combination with the Get-Cluster and Get-VMHosts cmdlets, Get-
VMHostStorage can quickly become very powerful; for example, the command below will rescan for new storage on
all of the hosts in Cluster 1:
As a virtual infrastructure admin you will, from time to time, need to carry out maintenance on a host server, whether
through patching or hardware replacement. As I’ve already alluded to, VMware provide some fantastic VMotion
technology within ESX and vCenter, which enables virtual machines to be transferred from one physical host to another
with no downtime incurred for the virtual machine. To move all VMs from one host to another, use this simple one
liner:
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Get-VMHost esx01 | Get-VM | Move-VM -Destination (Get-VMHost esx02)
Of course, you may not have enough resources on the target host to move all VMs across, and consequently might wish
to distribute them more evenly across a number of hosts. Wrapping all that lovely technology into just one elegant step,
the short script below will VMotion all of the virtual machines from one host in a cluster to random other hosts within
the same cluster.
First of all, the name of the source host will be stored in the variable $sourcehostname. Then we retrieve all of the
hosts within Cluster 1, drop the source host from that list, and store the results in $clusterhosts. Next, we retrieve all of
the virtual machines on the source host, storing them in $vms, and finally we cycle through each virtual machine,
generate a random target host and move the VM to that target host.
In a similar way to how the VMotion technology migrates a virtual machine from one physical host to another, it is also
possible to move the disks for a virtual machine between datastores whilst the virtual machine remains online – this
technology is known as Storage VMotion. This is even possible between different SANs, provided the hosts are
configured to see storage on both old and new SANs and there is sufficient bandwidth to transfer the necessary data.
Let’s say you have mapped out in, a CSV file, which datastore the disks for each virtual machine are moving to:
We can bring that data into the PowerShell session with the Import-CSV cmdlet, and then feed it into the Get-
VM and Move-VM cmdlets to Storage VMotion those virtual machines to the new SAN.
Note that the Import-CSV cmdlet will take the column headers in the CSV file and enable access to them as property
labels; i.e. for line 2, $vm.name is Server01 and $vm.targetdatastore is Datastore1_NEW.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
When carrying out such a SAN migration, you may wish to carry out the work outside of normal office hours to take
advantage of low-use periods on the SAN, and consequently move the data quicker. So, why not create a Windows
Scheduled Task to kick off the above script and schedule it for the required time? If you wanted to be really smart, you
could use the Send-MailMessage PowerShell cmdlet to have it email you each time a Storage VMotion completes.
Deploying new virtual machines is a simple task, particularly if you’ve created a base template and use the Guest
Customisation feature to sysprep a new Windows virtual machine. However, even this process can quickly become
tedious if you’re deploying multiple virtual machines from the GUI.
Let’s take an example where you have the requests for five new virtual machines provided to you in a CSV file:
The virtual machines can be easily deployed by, once again, using Import-CSV to read in the input data. Then we cycle
through the virtual machines and, for each deployment, get the template, host,datastore and customization to use, before
finally executing the New-VM cmdlet and feeding it those various parameters to use for creating each VM:
Keeping the networking configuration consistent and accurate across all ESX / ESXi hosts in a cluster is crucial. This is
particularly the case for technologies like VMotion, which requires identically configured networking on the source and
target hosts to enable virtual machines to transfer between them. In an enterprise environment, it would be very
common to have multiple VLANs made available via multiple port groups on different vSwitches. Consequently, when
deploying a new ESX / ESXi host into a cluster, a significant amount of manual networking configuration could be
required, which could easily lead to mistakes being made, and one very bored administrator.
To address this, VMware have introduced some new technology into vSphere 4.0, known as Host Profiles; however this
is only available to customers who have purchased Enterprise Plus licensing. Well known PowerCLI community expert
Alan Renouf has provided a simple alternative solution to this problem via his blog (rather than reproduce the script
here, I recommend you take a look at his blog once you’ve finished here. I’ll include a link at the end of the article).
This short script will prompt the administrator for a source and target host, copy the network configuration from the
source host and apply it to the target. Simple, yet very effective, and a great time saver; and no requirement to use Host
Profiles.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
8) Configuring an NTP Time Server
Another item to keep consistently configured across the ESX / ESXi hosts is the NTP server used to keep the time.
Whether setting this on a new host or making a change across all hosts, it’s a snap to do it with PowerCLI. To add an
NTP server to a new host, esx01, not previously configured use:
Or to first of all clear existing NTP server(s) then set the new one:
As mentioned at the beginning of the article, there is an additional set of commands which can be used in conjunction
with VMware Update Manager to assist with the automation of patching ESX / ESXi hosts or VMs. When planning a
patch deployment, it might be necessary to provide information up front to management regarding the list of patches
which you intend to install. Whilst VMware Update Manager has a GUI which is useful for most tasks, it is difficult to
extract this information out from the GUI and into a distributable format.
The code below will find the compliance status of a host, as scanned against a baseline, and then export a list of patches
required by that host out to a CSV file:
$ComplianceStatus.NotCompliantPatches |
Or how about bringing any newly installed ESX / ESXi host immediately up-to-date with the current standard patch
baseline? Easy.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
– Remediate the host against the required baseline:
These commands could all be added to a short script to be run at the end of a build process, to ensure that all newly
deployed hosts are at the required patch level.
The previously mentioned PowerCLI community expert, we have put together an amazing and, very generously,
completely free PowerShell reporting script, which can be run against a vCenter environment and report back on many
common issues and best practises.
Connect-VIServer -Server VCName
get-vm | % { get-view $_.ID } | select Name, @{ Name="hostName"; Expression={$_.guest.hostName}}, @{
Name="ToolsStatus"; Expression={$_.guest.toolsstatus}}, @{ Name="ToolsVersion"; Expression=
{$_.config.tools.toolsVersion}} | sort-object name > C:\VM.xls
==============
CLS
12)Powershell Script to get CPU and Memory Utilization of Multiple Virtual Machines
$allvms = @()
$vms = Get-Vm server1, server2, server3
$start = "12/15/2013 06:00 PM"
$FInish = "12/15/2013 11:59 PM"
$metrics = "cpu.usage.average","mem.usage.average"
$stats = Get-Stat -Entity $vms -Start $start -Finish $Finish -Stat $metrics
$stats | Group-Object -Property {$_.Timestamp.Day},{$_.Entity.Name} | %{
$vmstat = "" | Select VmName, Day, MemMax, MemAvg, MemMin, CPUMax, CPUAvg, CPUMin
$vmstat.VmName = $_.Values[1]
$vmstat.Day = $_.Group[0].Timestamp.Date
$cpu = $_.Group | where {$_.MetricId -eq "cpu.usage.average"} | Measure-Object -Property value -Average -
Maximum -Minimum
$mem = $_.Group | where {$_.MetricId -eq "mem.usage.average"} | Measure-Object -Property value -Average -
Maximum -Minimum
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
$vmstat.CPUMax = [int]$cpu.Maximum
$vmstat.CPUAvg = [int]$cpu.Average
$vmstat.CPUMin = [int]$cpu.Minimum
$vmstat.MemMax = [int]$mem.Maximum
$vmstat.MemAvg = [int]$mem.Average
$vmstat.MemMin = [int]$mem.Minimum
$allvms += $vmstat
}
$allvms
Connect-VIServer -Server VCName
get-vm | % { get-view $_.ID } | select Name, @{ Name="hostName"; Expression={$_.guest.hostName}}, @{
Name="ToolsStatus"; Expression={$_.guest.toolsstatus}}, @{ Name="ToolsVersion"; Expression=
{$_.config.tools.toolsVersion}} | sort-object name > C:\VM.xls
==============
CLS
Connect-VIServer VCName
Function Percentcal {
param(
[parameter(Mandatory = $true)]
[int]$InputNum1,
[parameter(Mandatory = $true)]
[int]$InputNum2)
$InputNum1 / $InputNum2*100
}
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
}
}
$datastores | Select Name,@{N=”UsedSpaceGB”;E={[Math]::Round(($_.ExtensionData.Summary.Capacity –
$_.ExtensionData.Summary.FreeSpace)/1GB,0)}},@{N=”TotalSpaceGB”;E=
{[Math]::Round(($_.ExtensionData.Summary.Capacity)/1GB,0)}} ,PercentFree | Export-Csv c:\datastorereport.csv -
NoTypeInformation
16)Get-LicenseInformation of vSphere
17)PowerCLI Script - Check VAAI Status of all ESXi Hosts in a Virtual Center
Connect-VIServer vCenterName
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
PowerCLI Script for VAAI. Save it as Get-VAAIStatus.ps1 and execute.
$vaaistatus = @()
Get-VMHost | %{
$DataMoverHardwareAcceleratedMove = $_ | Get-VMHostAdvancedConfiguration -Name
DataMover.HardwareAcceleratedMove
$VMFS3HardwareAcceleratedLocking = $_ | Get-VMHostAdvancedConfiguration -Name
VMFS3.HardwareAcceleratedLocking
$DataMoverHardwareAcceleratedInit = $_ | Get-VMHostAdvancedConfiguration -Name
DataMover.HardwareAcceleratedInit
$vaaistatus += new-object psobject -property @{
Host = $_.Name
DataMoverHardwareAcceleratedMove = [string]$DataMoverHardwareAcceleratedMove.Values
VMFS3HardwareAcceleratedLocking = [string]$VMFS3HardwareAcceleratedLocking.Values
DataMoverHardwareAcceleratedInit = [string]$DataMoverHardwareAcceleratedInit.Values
}
}
$vaaistatus
18)PowerCLI Script - Check VAAI Status of all ESXi Hosts in a Virtual Center
Use this PowerCLI Script to Check the Status of VAAI of all ESXi Hosts in Virtual Center
Connect-VIServer vCenterName
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Use below Powershell CLI command to configure maximum powershell memory.
PS C:\> sl WSMan:\localhost\Shell
PS WSMan:\localhost\Shell> dir
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Shell
Method#2
Other PowerCLI commands can also be use to check and configure powershell Memory. Open Powershell CLI. Run
below commands.
Get-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024
Method#3
You can also configure powershell Memory through batch command. Open CMD and run below command to configure
it.
winrm.cmd set winrm/config/winrs @{MaxMemoryPerShellMB="1024"}
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Method#4
You can also configure MaxMemoryPerShellMB in multiple machine remotely by using below batch command. Open
CMD and run below command to configure it.
for /f %%i in (servers.txt) do (
echo %%i
psexec \\%%i -s winrm.cmd quickconfig -q
psexec \\%%i -s winrm.cmd set winrm/config/winrs @{MaxMemoryPerShellMB="512"}
)
20)Powershell Script to Copy and Install *exe Setup to Multiple Remote Server
While installing any software to multiple remote computers, you may required some automation to avoid manual
efforts. Use below powershell script to perform this installation. It will copy setup file to destination folder and execute
installation.
#Variables
$computername = Get-Content servers.txt
$sourcefile = "\\server01\Pranay\setup.exe"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\Temp"
#It will copy $sourcefile to the $destinationfolder. If the Folder does not exist it will
create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Invoke-Command -ComputerName $computer -ScriptBlock {Start-Process 'c:\temp\setup.exe'}
}
21)Powershell - Get OS Architecture of Multiple Computer(64 bit or 32 bit OS)
Powershell Script to Check to Get OSArchitecture of Multiple Computers. Check if Computer is 64 bit
or 32 bit
$servers = get-content servers.txt
During one of the activity we performed in our orgnaziation to rebuild Virtual Center, we faced issue that few of the
admins were reporting access issue. It was because if we rebuild virtual center, it didn't add existing Roles and
Permissions in Virtual Center. Hence I planned to export roles from one vcenter to this newly rebuilt vcenter. However
creating manual roles and adding to permission take longer if we have large number of users listed in ACL. Hence
performed automation through below script to reduce manual efforts. It worked perfectly and save few hours.
# Variables
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
$VC1="vCenter1"
$VC2="vCenter2"
# Set the PowerCLI Configuration to connect to multiple vCenters
Set-PowerCLIConfiguration -DefaultVIServerMode multiple -Confirm:$false
# Connect to both the source and destination vCenters
connect-viserver -server $VC1, $VC2
# Get roles to transfer
$roles = get-virole -server $VC1
# Get role Privileges
foreach ($role in $roles) {
[string[]]$privsforRoleAfromVC1=Get-VIPrivilege -Role (Get-VIRole -Name $role -server $VC1) |%{$_.id}
# Create new role in VC2
New-VIRole -name $role -Server $VC2
# Add Privileges to new role.
Set-VIRole -role (get-virole -Name $role -Server $VC2) -AddPrivilege (get-viprivilege -id $privsforRoleAfromVC1 -
server $VC2)
}
disconnect-viserver –server $VC1, $VC2
23)Connect-VIServer | Error: The HTTP request was forbidden with client authentication scheme 'Anonymous'
Error: The HTTP request was forbidden with client authentication scheme 'Anonymous'
Solution:-
This error message pop up because of invalid certificate on your local machine which is unable to match with your
Virtual center certificate. To get this fix, either use a valid certificate.
As an alternative workaround, you can use below command to ignore invalid certificate error.
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
This will help you to find the load of the ESXi Sever. Here you can find the services running with their process ID &
Name. It will also display the average CPU load.
esxtop
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
Using this command you can start or stop the services in the ESXi.
services.sh
file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]