0% found this document useful (0 votes)
410 views

PowerCLI Scripting For VMware VSphere

The document discusses ESXi command line (ESXCLI) commands. It provides a table listing available ESXCLI namespaces and descriptions. It then discusses the top 20 most used ESXCLI commands, grouping them under system, network, software, virtual machine, storage, and iSCSI related commands. Each command is accompanied by a brief description. The document aims to help users learn and use basic ESXCLI commands.

Uploaded by

Vishal Mulik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
410 views

PowerCLI Scripting For VMware VSphere

The document discusses ESXi command line (ESXCLI) commands. It provides a table listing available ESXCLI namespaces and descriptions. It then discusses the top 20 most used ESXCLI commands, grouping them under system, network, software, virtual machine, storage, and iSCSI related commands. Each command is accompanied by a brief description. The document aims to help users learn and use basic ESXCLI commands.

Uploaded by

Vishal Mulik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Basic 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 Top 20 ESXCLI Commands

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.

System related commands

#1: esxcli system version get

Description: Returns the ESXi build and version numbers.

file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
 

#2: esxcli system hostname get

Description: Returns the hostname, domain and FQDN for the host.

#3: esxcli system stats installtime get

Description: Returns the date and time of when ESXi was installed.

#4: esxcli system account list

Description: Lists the local users created on the ESXi host.

#5: esxcli system account add -d=”Altaro Guest” -i=”altaro” -p=”dsfewfewf*3!4404″ -c=”dsfewfewf*3!4404″

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.

#6: esxcli system maintenanceMode set –enable true

Description: Use this command to put ESXi in maintenance mode or take it out.

#7: esxcli system shutdown reboot -d 10 -r “Patch Updates”

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.

Network related commands

#8: esxcli network firewall get

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

#9: esxcli network firewall set –enabled true | false

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.

#10: esxcli network firewall ruleset list | awk ‘$2 ==”true”‘

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.

#11: esxcli network ip interface ipv4 get

Description: Displays the IPv4 configuration for all the interfaces present on ESXi.

Software related commands

#12: esxcli software vib list

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]
 

#13: esxcli software vib update -d “/tmp/update.zip”

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.

Virtual Machine related commands

#14: esxcli vm process list

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.

#15: esxcli vm process kill -w 69237 -t soft

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]
 

Storage related commands

#16: esxcli storage vmfs extent list

Description: The command generates a list of extents for each volume as well as the corresponding device name to
UUID mapping.

#17: esxcli storage filesystem list

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.

iSCSI related commands

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

#19: esxcli iscsi adapter param get -A vmhba65

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]
 

Available ESXCLI commands

#20: esxcli esxcli command list

Description: Lists all the available namespaces and corresponding commands.

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.

Basic PowerCLI scripting

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.

To connect, run the following command in a PowerCLI enabled PowerShell session:

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.

Get-VM | where-object {$_.PowerState –eq “PoweredOff”}

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.

Get-VM | where-object {$_.PowerState –eq “PoweredOff”} | Start-VM

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.

Get-VM 〈yourvm〉 | Stop-VMguest

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.

Get-VM | where-object {$_.NumCpu –gt 1 }

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:

foreach ($var in $vars){


Do something…
}

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.

Get-vm | where-object {$_.MemoryGB –eq 4 } | select -ExpandProperty Name | out-file c:\VMs.txt


$vms = get-content c:\VMs.txt
Foreach-object ($vm in $vms) {
new-networkadapter -vm $vms -NetworkName “〈Port group name〉” -Type “VMXNET3” –startconnected
}

Steps to Kick Start Automation

1) Reviewing and Configuring Virtual Machines

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.

Get-VM | Select-Object Name,NumCPU,MemoryMB,PowerState,Host |


 
    Export-CSV VMs.csv -NoTypeInformation

A sample result of which is shown below:

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):

Get-VM | Where-Object {$_ | Get-CDDrive |

      Where-Object { $_.ConnectionState.Connected -eq "true"  } } |

    Select-Object Name

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:

Get-VM | Where-Object {$_ | Get-CDDrive |

      Where-Object { $_.ConnectionState.Connected -eq "true"  } } |

    Get-CDDrive | Set-CDDrive -Connected $false -Confirm:$false

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.

2) Basic Capacity Information

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:

# Total number of hosts

$TotalVMHosts = (Get-VMHost).Count

Write-Host "There are $TotalVMHosts Hosts in $DefaultVIServer"

# Total number of guests

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

# Average VMs Per Cluster

  $Clusters = Get-Cluster

foreach ($Cluster in $Clusters){

    $VMHosts = Get-Cluster $Cluster | Get-VMHost

    $VMs = Get-Cluster $Cluster | Get-VM

    $AverageVMsPerCluster = [math]::round(($VMs.count / $VMHosts.count), 1)

    Write-Host "$Cluster has $AverageVMsPerCluster guests per VMware host"

3) Rescanning for New Storage

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:

Get-Cluster 'Cluster 1' | Get-VMHost |


 
    Get-VMHostStorage -RescanAllHba -RescanVmfs

4) VMotion Virtual Machines to other Hosts

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.

$sourcehostname = (Get-VMHost 'esx01').name

$clusterhosts = Get-Cluster 'Cluster 1' | Get-VMHost |

    Where-Object {$_.name -notlike "$sourcehostname"}

$vms = Get-VMHost $sourcehostname | Get-VM

  

foreach ($vm in $vms){

      $targethost = $clusterhosts | Get-Random

      Move-VM -VM $vm -Destination $targethost

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.

5) Storage VMotion Virtual Machines to a New SAN

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.

$vms = Import-CSV C:\Scripts\SVMotion.csv

  foreach ($vm in $vms){

      Get-VM $vm.name | Move-VM -Datastore $vm.targethostname

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.

6) Deploying Virtual Machines from a Template

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:

$vms = Import-CSV C:\Scripts\NewVMs.csv

foreach ($vm in $vms){

      $Template = Get-Template $vm.template

      $VMHost = Get-VMHost $vm.host


 
      $Datastore = Get-Datastore $vm.datastore

      $OSCustomization = Get-OSCustomizationSpec $vm.customization

      New-VM -Name $vm.name -OSCustomizationSpec $OSCustomization `

        -Template $Template -VMHost $VMHost -Datastore $Datastore -RunAsync

7) Configuring vSwitches and Port Groups

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:

  Get-VMHost esx01 | Add-VMHostNtpServer -NtpServer ntpservername

Or to first of all clear existing NTP server(s) then set the new one:

Get-VMHost esx01 | Remove-VMHostNtpServer `

      -NtpServer (Get-VMHost esx01 | Get-VMHostNtpServer)

Get-VMHost esx01 | Add-VMHostNtpServer -NtpServer ntpservername

9) Patching Via VMware Update Manager

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 = Get-Compliance -Entity 'esx01' -Detailed

$ComplianceStatus.NotCompliantPatches |

    Select-Object Name,IDByVendor,Description,`


 
        @{n='Product';e={$_.product |

        Select-Object -expandproperty Version}},ReleaseDate |

    Export-Csv patches.csv -NoTypeInformation

Or how about bringing any newly installed ESX / ESXi host immediately up-to-date with the current standard patch
baseline? Easy.

Retrieve the required baseline:

  $Baseline = Get-Baseline "Current ESX Baseline"

Attach the baseline to the required ESX / ESXi host:

  $Baseline | Attach-Baseline -Entity esx01

Scan the host to determine required patches:

  Scan-Inventory -Entity esx01

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:

  $Baseline | Remediate-Inventory -Entity esx01 -Confirm:$false

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.

10) Schedule the vCheck Reporting Script to Run Daily

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.

11)Powershell Script to Start or Stop SSH Service on ESXi Hosts in Cluster

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

==============

#Uncomment if this SnapIn has not been added


#Add-PSSnapIn VMware.VimAutomation.Core

CLS

$creds = Get-VICredentialStoreItem -file “C:\powercli\credfile.xml”


Connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password

Get-VM | Get-View | Select-Object @{N=”VM Name”;E={$_.Name}},@{Name=”VMware Tools”;E=


{$_.Guest.ToolsStatus}} | Export-CSV c:\powercli\VMwareToolsStatus.csv

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

13)Powershell Script to Get VM Tool Status of Virtual Machines in vCenter

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

==============

#Uncomment if this SnapIn has not been added


#Add-PSSnapIn VMware.VimAutomation.Core

CLS

$creds = Get-VICredentialStoreItem -file “C:\powercli\credfile.xml”


Connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password

Get-VM | Get-View | Select-Object @{N=”VM Name”;E={$_.Name}},@{Name=”VMware Tools”;E=


{$_.Guest.ToolsStatus}} | Export-CSV c:\powercli\VMwareToolsStatus.csv

14)Powershell Script to get Datastores Information in vCenter

Connect-VIServer VCName
Function Percentcal {
    param(
    [parameter(Mandatory = $true)]
    [int]$InputNum1,
    [parameter(Mandatory = $true)]
    [int]$InputNum2)
    $InputNum1 / $InputNum2*100
}

$datastores = Get-Datastore | Sort Name


ForEach ($ds in $datastores)
{
    if (($ds.Name -match “Shared”) -or ($ds.Name -match “”))
    {
        $PercentFree = Percentcal $ds.FreeSpaceMB $ds.CapacityMB
        $PercentFree = “{0:N2}” -f $PercentFree
        $ds | Add-Member -type NoteProperty -name PercentFree -value $PercentFree

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

15)Powershell Script to Change VLAN of Multiple Virtual Machines

# VCenter you are connecting too


$vcserver = "vc01"
Connect-VIServer $vcserver
# Loop to make changes to Network Adapter from List of Servers that needs to be changed
$serverlist = Get-Content "C:\Users\pranay\Desktop\vlan.txt"
ForEach ($server in $serverlist)
{
$NIC = Get-NetworkAdapter -VM $server
Set-NetworkAdapter -NetworkAdapter $NIC -NetworkName "VLAN100"
}

16)Get-LicenseInformation of vSphere

# Set to multiple VC Mode


#if(((Get-PowerCLIConfiguration).DefaultVIServerMode) -ne "Multiple") {
#    Set-PowerCLIConfiguration -DefaultVIServerMode Multiple | Out-Null
#}

# Make sure you connect to your VCs here

# Get the license info from each VC in turn


$vSphereLicInfo = @()
$ServiceInstance = Get-View ServiceInstance
Foreach ($LicenseMan in Get-View ($ServiceInstance | Select -First 1).Content.LicenseManager) {
    Foreach ($License in ($LicenseMan | Select -ExpandProperty Licenses)) {
        $Details = "" |Select VC, Name, Key, Total, Used, ExpirationDate , Information
        $Details.VC = ([Uri]$LicenseMan.Client.ServiceUrl).Host
        $Details.Name= $License.Name
        $Details.Key= $License.LicenseKey
        $Details.Total= $License.Total
        $Details.Used= $License.Used
        $Details.Information= $License.Labels | Select -expand Value
        $Details.ExpirationDate = $License.Properties | Where { $_.key -eq "expirationDate" } | Select -ExpandProperty
Value
        $vSphereLicInfo += $Details
    }
}
$vSphereLicInfo | Format-Table -AutoSize

17)PowerCLI Script - Check VAAI Status of all ESXi Hosts in a Virtual Center

Run below command in PowerCLI to Connect 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

Run below command in PowerCLI to Connect Virtual Center.

Connect-VIServer vCenterName

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
19)How to Configure Maximum Powershell Memory (MaxMemoryPerShellMB) in Windows Server

Configure Maximum Powershell Memory (MaxMemoryPerShellMB) in


Windows Server
Method#1

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

Type            Name                           SourceOfValue   Value


----            ----                           -------------   -----
System.String   AllowRemoteShellAccess                         true
System.String   IdleTimeout                                    7200000
System.String   MaxConcurrentUsers                             10
System.String   MaxShellRunTime                                2147483647
System.String   MaxProcessesPerShell                           25
System.String   MaxMemoryPerShellMB                            512
System.String   MaxShellsPerUser                               30

PS WSMan:\localhost\Shell> Set-Item .\MaxMemoryPerShellMB 1024

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

foreach ($srv in $servers){


$result=Get-WMIObject Win32_OperatingSystem -ComputerName $srv | Select-Object csname,
OSArchitecture
$result | out-file -Append out.txt

22)Migrate Roles & Permissions from one vCenter to another vCenter

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'

While connecting Virtual Center through powerCLI, I got below error.

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.

Set-PowerCLIConfiguration -InvalidCertificateAction ignore

file:///D/Downloads/VMware%20vSphere.ver.1.0.build.9/assets/Powershell.html[25-02-2019 00:18:45]
 

Basic commands for ESXi :


Basic commands includes the basic operations which you can do in the ESXi console such as listing the directories,
changing the directory, checking the date etc etc.
Commands:
ls >listing the directory.
ls -l >to check the directories with details.
pwd >finding the present working directory.
cd >change the working directory.
date >finding the date & time.

Finding the ESXi version & updates:


This will help you to find the ESXi version with build numbers & the installed VIB’s.
vmware -l   >For ESXi version
vmware -v  >For ESXi version with build 
esxcli software vib list   >For checking installed VIB.

Finding the Hostname & IP address:


Basic command to find the ESXi host name & IP address.
hostname    >For finding the hostname
hostname -i    >For finding IP address.

Monitoring the ESXi load:

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

Start or Stop the services:

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]

You might also like