VMware OneLiners and Cheat Sheet

These cheat sheets are to be used on the VMware platform. Some VMware oneliners require PowerCLI; others can be run directly on the Photon OS on your ESX host.

powercli

Do you like OneLiners? Me too. Check out our featured one-liners for:

PowerShell OneLiners

Active Directory Oneliners


Restart VMWare Management Services on a Host

The services hostd and vpxa play a crucial role in the management layer. They enable seamless communication between the ESXi host and the vCenter Server and directly manage many host operations. Sometimes, these services experience issues, or you might need to restart them after a configuration change.

Bash
/etc/init.d/hostd restart
/etc/init.d/vpxa restart

Command Explanation

  • /etc/init.d/hostd restart: The hostd service acts as the core service that operates directly on an ESXi host. It is responsible for managing most of the operations on the host and is pivotal for the host’s communication with the vCenter Server. Executing this command will restart the hostd service, which can resolve issues related to host management or reinitialize the service after updates.
  • /etc/init.d/vpxa restart: The vpxa service is the vCenter Server agent, which also resides on the ESXi host. This service is in charge of forwarding requests between the ESXi host and the vCenter Server. Restarting the vpxa service with this command can alleviate problems tied to vCenter-ESXi communication and is often required after changes to the vCenter Server configuration.

Check if Change Block Tracking enabled on VM

Change Block Tracking (CBT) is a VMware feature that significantly improves incremental backup efficiency. CBT allows backup software to back up only the changed blocks instead of the entire virtual disk by monitoring and recording the blocks that have changed since the last backup. It is crucial to know the CBT status of your virtual machines (VMs) to ensure effective backup strategies.

Bash
(Get-VM -Name Server_Name).ExtensionData.Config.ChangeTrackingEnabled
(Get-VM-Name Server_Name).ExtensionData.Config.ChangeTrackingEnabled
# Find VMs where CBT (Change Block Tracking) is Enabled
Get-VM| Where-Object{$_.ExtensionData.Config.ChangeTrackingEnabled-eq $true}

Command Explanation

  • (Get-VM -Name Server_Name).ExtensionData.Config.ChangeTrackingEnabled: This PowerShell command fetches the CBT status of a specific VM by its name. By running this command, you’ll determine whether Change Block Tracking is enabled (True) or disabled (False). It queries the ExtensionData.Config property of the VM object to find the value of ChangeTrackingEnabled.
  • Get-VM| Where-Object{$_.ExtensionData.Config.ChangeTrackingEnabled -eq $true}: This command takes a more extensive approach by checking all VMs in your environment. It lists the VMs where CBT is enabled. The command uses the Where-Object cmdlet to filter out VMs based on the value of their ChangeTrackingEnabled property.

Get VM NIC with E1000 Network Adapter

The E1000 is a type of emulated NIC provided by VMware, often used for compatibility purposes but not recommended for production due to its performance overhead. To ensure optimal performance and security, it’s important to identify VMs that are still using this older NIC type.

Bash
Get-VM | Get-NetworkAdapter | Select @{N='VM';E={$_.Parent.Name}},@{N='AdapterName';E={$_.Name}},@{N='Type';E={$_.Type}} | Where-Object{$_.Type -eq "e1000"}

Command Explanation

  • Get-VM | Get-NetworkAdapter | Select @{N='VM';E={$_.Parent.Name}},@{N='AdapterName';E={$_.Name}},@{N='Type';E={$_.Type}} | Where-Object{$_.Type -eq "e1000"}: This PowerShell command performs several operations to identify VMs with E1000 NICs.
    1. Get-VM: Fetches all virtual machines in your environment.
    2. Get-NetworkAdapter: Retrieves the network adapter details of the fetched VMs.
    3. Select @{N='VM';E={$_.Parent.Name}},@{N='AdapterName';E={$_.Name}},@{N='Type';E={$_.Type}}: Customizes the output to show only relevant information. It selects the VM name (VM), the adapter name (AdapterName), and the type of NIC (Type).
    4. Where-Object{$_.Type -eq "e1000"}: Filters the results to display only the VMs with E1000 NICs.

Get VM IP

Knowing the IP addresses of your virtual machines (VMs) facilitates seamless networking, troubleshooting, and administration tasks. Whether you’re diagnosing connectivity issues or configuring network policies, obtaining the IP addresses of your VMs can be very beneficial.

Bash
Get-vm | Select Name, @{N="IP Address";E={@($_.guest.IPAddress[0])}}

Command Explanation

  • Get-vm | Select Name, @{N="IP Address";E={@($_.guest.IPAddress[0])}}: This command is a one-liner that provides a concise and efficient way to obtain VM IP addresses.
    1. Get-vm: This initiates the command by fetching all virtual machines currently in your VMware setup.
    2. Select Name, @{N="IP Address";E={@($_.guest.IPAddress[0])}}: This segment structures the output to display only the relevant information. Specifically, it shows the name of the VM (Name) and its IP address (IP Address).
      • @{N="IP Address";E={@($_.guest.IPAddress[0])}}: This is a calculated field that extracts the first IP address from the IPAddress array of the VMs guest property.

Get VM Name, cluster, ESX , Datastore – and sort by Datastore

Whether you’re balancing storage capacity or planning migrations, knowing the relationships between your Virtual Machines (VMs), clusters, ESX hosts, and datastores can offer invaluable insights. The following command provides a way to collate this information for every VM and sorts the results by datastore, which can be especially useful for storage management or auditing.

Bash
Get-VM | Select Name, @{N="Cluster";E={Get-Cluster -VM $_}}, @{N="ESX Host";E={Get-VMHost -VM $_}}, @{N="Datastore";E={Get-Datastore -VM $_}} |sort-object Datastore

Command Explanation

  • Get-VM | Select Name, @{N="Cluster";E={Get-Cluster -VM $_}}, @{N="ESX Host";E={Get-VMHost -VM $_}}, @{N="Datastore";E={Get-Datastore -VM $_}} | Sort-Object Datastore: This PowerShell command carries out multiple operations to obtain and organize critical VM information.
    1. Get-VM: The command begins by gathering all the VMs in your VMware environment.
    2. Select Name, @{N="Cluster";E={Get-Cluster -VM $_}}, @{N="ESX Host";E={Get-VMHost -VM $_}}, @{N="Datastore";E={Get-Datastore -VM $_}}: This portion structures the output. It includes the VM name (Name), the associated cluster (Cluster), the ESX host (ESX Host), and the datastore (Datastore).
      • For each VM, the command dynamically fetches its associated cluster using Get-Cluster -VM $_, its ESX host with Get-VMHost -VM $_, and its datastore using Get-Datastore -VM $_.
    3. Sort-Object Datastore: Finally, the output is sorted based on the datastore name, making it easier to identify VMs that share the same storage resource.
Elsewhere On TurboGeek:  PowerShell OneLiners for Active Directory

Query the nic type of all virtual machines

Different NIC types come with distinct advantages and limitations, and choosing the right one can significantly affect your VMs’ networking efficiency. The following PowerShell command enables you to query the NIC type for all virtual machines in your VMware setup, providing a comprehensive overview for network planning or troubleshooting.

Bash
Get-VM | Get-NetworkAdapter | Select-Object Parent,Type

Command Explanation

  • Get-VM | Get-NetworkAdapter | Select-Object Parent,Type: This PowerShell command performs a series of actions to list the NIC type for each VM.
    1. Get-VM: Initially, this command fetches all the virtual machines in your VMware environment.
    2. Get-NetworkAdapter: This component retrieves the network adapter information for the acquired list of VMs.
    3. Select-Object Parent,Type: Lastly, this segment narrows down the output to display only the name of the VM (Parent) and the type of its NIC (Type).

Query the disk type of all virtual machines

Disk performance and efficiency are essential aspects of virtual machine management. Different storage formats have unique characteristics that can impact not just the VM performance but also the storage efficiency in your datacenter. For example, formats like Thick Provision Lazy Zeroed, Thick Provision Eager Zeroed, and Thin Provision each come with their own sets of advantages and trade-offs. To effectively manage your virtualized environment, it’s useful to know what disk types your VMs are using. The following PowerShell command can provide you with this valuable information

Bash
get-vm | foreach-object -process {get-harddisk $_} | select-object storageformat | format-list

Command Explanation

  • get-vm | foreach-object -process {get-harddisk $_} | select-object storageformat | format-list: This command strings together several cmdlets to fetch and display the storage formats of all hard disks across your virtual machines.
    1. get-vm: This initiates the sequence by fetching all virtual machines in your VMware environment.
    2. foreach-object -process {get-harddisk $_}: For each VM fetched, this part of the command retrieves its associated hard disks using the get-harddisk cmdlet.
    3. select-object storageformat: Here, the output is filtered to include only the storageformat property of each hard disk, which indicates its type.
    4. format-list: Finally, this cmdlet formats the output as a list for better readability.

Get snapshots older than 3 months

While snapshots are invaluable for tasks like backup and disaster recovery, keeping them for an extended period can consume substantial disk space and may lead to performance degradation. It is a good practice to identify and manage older snapshots, particularly those that have outlived their usefulness.

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

Command Explanation

  • Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-90)} | Select-Object VM, Name, Created, SizeMB: This command chain performs multiple actions to list snapshots that are older than 90 days.
    1. Get-VM: Initially, the command retrieves all the virtual machines in your VMware environment.
    2. Get-Snapshot: For each VM, this part gathers all associated snapshots.
    3. Where {$_.Created -lt (Get-Date).AddDays(-90)}: This filtering clause compares the creation date of each snapshot to the current date minus 90 days. Only snapshots older than this threshold are included in the output.
    4. Select-Object VM, Name, Created, SizeMB: Finally, this segment organizes the output to show the VM associated with the snapshot (VM), the name of the snapshot (Name), its creation date (Created), and its size in megabytes (SizeMB).

Get Snapshots and Delete Them

Snapshots are a useful feature for capturing the state of a virtual machine, but their prolonged existence can lead to storage issues and suboptimal performance. Periodic review and clean-up of old snapshots are advisable for maintaining an efficient virtualized environment.

Bash
Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-120)} | Remove-Snapshot -Confirm:$false

Command Explanation

  • Get-VM | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-120)} | Remove-Snapshot -Confirm:$false: This command chain performs multiple tasks aimed at identifying and removing older snapshots.
    1. Get-VM: This first step fetches all the virtual machines available in your VMware setup.
    2. Get-Snapshot: This action collects all snapshots associated with each of the fetched VMs.
    3. Where {$_.Created -lt (Get-Date).AddDays(-120)}: This filtering step compares the creation date of each snapshot with the current date minus 120 days. Only snapshots older than this cut-off are considered for removal.
    4. Remove-Snapshot -Confirm:$false: The final action removes the selected snapshots without requiring confirmation.

Please note that this command will automatically delete the selected snapshots without any further confirmation. Make sure to thoroughly verify the list of snapshots to be deleted, especially if they are associated with critical systems or data.


Count number of snapshots

Keeping track of the number of snapshots for each virtual machine is crucial for effective storage management and performance optimization. Excessive snapshots can consume a significant amount of storage space and could negatively affect VM performance. The following PowerShell command is designed to count the number of snapshots for each VM in your VMware environment, providing a quick overview that can aid in snapshot management.

Bash
Get-VM | Format-Table Name, @{Label="NumSnapshots";Expression={(Get-Snapshot -VM $_ | Measure-Object).Count}}

Command Explanation

  • Get-VM | Format-Table Name, @{Label="NumSnapshots";Expression={(Get-Snapshot -VM $_ | Measure-Object).Count}}: This command amalgamates several PowerShell cmdlets to compute and display the number of snapshots for each virtual machine.
    1. Get-VM: The command starts by fetching all virtual machines in your VMware setup.
    2. Format-Table Name, @{Label="NumSnapshots";Expression={(Get-Snapshot -VM $_ | Measure-Object).Count}}: This segment structures the output as a table, including the name of each VM (Name) and the number of its snapshots (NumSnapshots).
      • @{Label="NumSnapshots";Expression={(Get-Snapshot -VM $_ | Measure-Object).Count}}: This calculated field dynamically fetches snapshots for each VM using Get-Snapshot -VM $_ and counts them using Measure-Object.

Get Vmware tools version

Keeping your VMware Tools up-to-date is essential for achieving optimal performance and security in a virtualized environment. VMware Tools include drivers and utilities that enhance the functionality of your virtual machines, including but not limited to improved mouse performance, better display resolutions, and accelerated storage. Therefore, knowing the version of VMware Tools installed on your VMs is beneficial for troubleshooting and management. The following PowerShell command provides a way to query this version information for all VMs.

Bash
get-vm |% { get-view $_.id } | select Name, @{ Name=";ToolsVersion";; Expression={$_.config.tools.toolsVersion}}

Command Explanation

  • get-vm |% { get-view $_.id } | select Name, @{ Name=";ToolsVersion"; Expression={$_.config.tools.toolsVersion}}: This command integrates multiple cmdlets and custom expressions to fetch and display the VMware Tools version for each virtual machine.
    1. get-vm: Initially, this part of the command retrieves all the virtual machines in your VMware environment.
    2. % { get-view $_.id }: This is a shorthand for ForEach-Object. For each VM, it fetches additional details through the get-view cmdlet by specifying the VM’s id.
    3. select Name, @{ Name=";ToolsVersion"; Expression={$_.config.tools.toolsVersion}}: This portion formats the output to include the name of the VM (Name) and its corresponding VMware Tools version (;ToolsVersion).
      • @{ Name=";ToolsVersion"; Expression={$_.config.tools.toolsVersion}}: This expression dynamically fetches the VMware Tools version from the configuration properties of each VM.
Elsewhere On TurboGeek:  Unlock the Power of WMI Commands: Troubleshooting and Optimization Made Easy

Upon execution, the command outputs a list that includes each VM’s name and the corresponding VMware Tools version.


Get time off hosts

Synchronized and accurate time settings are critical for a variety of functions within a virtualized environment, including logging, auditing, and even certain application functions. Time drift on ESXi hosts can lead to significant issues such as authentication failures, logging discrepancies, and other time-sensitive operations failing. Therefore, regularly checking the system time on your ESXi hosts is a best practice that can prevent a range of issues.

Bash
get-vmhost | select Name,@{Name="Time";Expression={(get-view $_.ExtensionData.configManager.DateTimeSystem).QueryDateTime()}}

Command Explanation

  • get-vmhost | select Name,@{Name="Time";Expression={(get-view $_.ExtensionData.configManager.DateTimeSystem).QueryDateTime()}}: This command combines multiple cmdlets and custom expressions to fetch and display the current time on each ESXi host in your VMware infrastructure.
    1. get-vmhost: This part of the command starts by retrieving all the ESXi hosts in your VMware setup.
    2. select Name,@{Name="Time";Expression={(get-view $_.ExtensionData.configManager.DateTimeSystem).QueryDateTime()}}: This segment formats the output to include both the name of each ESXi host (Name) and its current time setting (Time).
      • @{Name="Time";Expression={(get-view $_.ExtensionData.configManager.DateTimeSystem).QueryDateTime()}}: The expression dynamically queries the current time setting from each host’s DateTimeSystem configuration.

Executing this command will yield a list that displays the name of each ESXi host along with its current time setting.


Get VMs and free disk space

Monitoring disk space utilization is paramount for maintaining a healthy and efficient virtualized environment. Running out of disk space can have a multitude of adverse effects, such as application failures, data loss, and service interruptions. Therefore, it’s crucial to periodically check the free disk space available on your virtual machines.

Bash
ForEach ($VM in Get-VM ){($VM.Extensiondata.Guest.Disk | Select @{N="Name";E={$VM.Name}},DiskPath, @{N="Capacity(MB)";E={[math]::Round($_.Capacity/ 1MB)}}, @{N="Free Space(MB)";E={[math]::Round($_.FreeSpace / 1MB)}}, @{N="Free Space %";E={[math]::Round(((100* ($_.FreeSpace))/ ($_.Capacity)),0)}})}

Command Explanation

  • ForEach ($VM in Get-VM ){($VM.Extensiondata.Guest.Disk | Select @{N="Name";E={$VM.Name}},DiskPath, @{N="Capacity(MB)";E={[math]::Round($_.Capacity/ 1MB)}}, @{N="Free Space(MB)";E={[math]::Round($_.FreeSpace / 1MB)}}, @{N="Free Space %";E={[math]::Round(((100* ($_.FreeSpace))/ ($_.Capacity)),0)}})}: This command incorporates various PowerShell cmdlets and expressions to fetch and display detailed disk space information for each VM.
    1. ForEach ($VM in Get-VM): This initial loop iterates through each VM fetched by the Get-VM cmdlet.
    2. ($VM.Extensiondata.Guest.Disk | Select ...): This part focuses on the disk data for each VM and pipes it through a selection command.
    3. Various expressions using @{N="Label";E={...}} are used to format the output, which includes:
    • VM Name (Name)
    • Disk Path (DiskPath)
    • Disk Capacity in MB (Capacity(MB))
    • Free Space in MB (Free Space(MB))
    • Percentage of Free Space (Free Space %)

The command uses the [math]::Round() function to round the disk capacity and free space to the nearest megabyte, and it calculates the percentage of free space with a rounded, whole number representation.


Get Host CPU info

Understanding the CPU specifications of your ESXi hosts is essential for effective resource allocation, troubleshooting, and performance optimization in a virtualized environment. Different workloads may require different CPU capabilities, and having detailed information about the CPUs in your hosts can aid in planning and decision-making.

Bash
Get-VMHost | Sort Name | Get-View | Select Name, @{N="CPU";E={$_.Hardware.CpuPkg[0].Description}}

Command Explanation

  • Get-VMHost | Sort Name | Get-View | Select Name, @{N="CPU";E={$_.Hardware.CpuPkg[0].Description}}: This command sequence integrates several cmdlets and expressions to extract and list CPU details for each host, sorted by the host’s name.
    1. Get-VMHost: The initial cmdlet gathers all ESXi hosts available in your VMware setup.
    2. Sort Name: This part sorts the list of hosts alphabetically by their names.
    3. Get-View: This cmdlet retrieves more granular details about each host.
    4. Select Name, @{N="CPU";E={$_.Hardware.CpuPkg[0].Description}}: This final segment of the command formats the output to include:
    • The name of the ESXi host (Name)
    • The description of the CPU (CPU)

The expression @{N="CPU";E={$_.Hardware.CpuPkg[0].Description}} dynamically fetches the description of the first CPU package from the hardware configuration of each ESXi host.


Get Detailed VM information

In a virtualized environment, having a comprehensive overview of each virtual machine’s (VM) characteristics is indispensable for effective management and troubleshooting. These characteristics can range from the basics like the number of CPUs to more specific details like the operating system, hardware abstraction layer (HAL), and service pack version.

Bash
$esxihost | Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"} | Sort-Object Name | Select-Object Name, NumCPU, @{N="OSHAL"; E={(Get-WmiObject -ComputerName $_.Name -Query "SELECT * FROM Win32_PnPEntity WHERE ClassGuid = '{4D36E966-E325-11CE-BFC1-08002BE10318}'" | Select-Object Name).Name}}, @{N="OperatingSystem"; E={(Get-WmiObject -ComputerName $_.Name -Class Win32_OperatingSystem | Select-Object Caption).Caption}}, @{N="ServicePack"; E={(Get-WmiObject -ComputerName $_.Name -Class Win32_OperatingSystem | Select-Object CSDVersion).CSDVersion}}

Command Explanation

  • $esxihost | Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"} | Sort-Object Name | Select-Object Name, NumCPU, ...: This complex command sequence combines multiple cmdlets and expressions to gather and display a detailed set of information about each VM.
    1. $esxihost | Get-VM: This section begins by fetching all VMs from the specified ESXi host stored in the $esxihost variable.
    2. Where-Object {$_.PowerState -eq "PoweredOn"}: This filter ensures that only VMs that are currently powered on are processed.
    3. Sort-Object Name: This sorts the list of VMs alphabetically by their names.
    4. Select-Object Name, NumCPU, ...: This part selects specific attributes to display, including:
    • VM Name (Name)
    • Number of CPUs (NumCPU)
    • Operating System HAL information (OSHAL)
    • Operating System Description (OperatingSystem)
    • Service Pack Version (ServicePack)

The command uses Get-WmiObject to query additional information like OSHAL, Operating System, and Service Pack from the Windows Management Instrumentation (WMI) on each VM. Multiple custom expressions are defined for collecting these details.


List how many VMs are running on a Host

In virtualized environments managed by VMware, understanding resource utilization per host is crucial for balanced workloads and optimized performance. One key metric in this context is the number of Virtual Machines (VMs) running on each host. Knowing this count helps system administrators in tasks like capacity planning, load balancing, and troubleshooting.

Bash
Get-VMHost | Select @{N="Cluster";E={Get-Cluster -VMHost $_}}, Name, @{N="NumVM";E={($_ | Get-VM).Count}} | Sort Cluster, Name

Command Explanation

  • Get-VMHost | Select @{N="Cluster";E={Get-Cluster -VMHost $_}}, Name, @{N="NumVM";E={($_ | Get-VM).Count}} | Sort Cluster, Name: This command string integrates multiple cmdlets and expressions to count the number of VMs on each ESXi host and sort them by cluster and host names.
    1. Get-VMHost: The initial cmdlet fetches all ESXi hosts within your VMware environment.
    2. Select @{N="Cluster";E={Get-Cluster -VMHost $_}}, Name, @{N="NumVM";E={($_ | Get-VM).Count}}: This segment formats the output to show:
    • The cluster name each host belongs to (Cluster)
    • The name of the ESXi host (Name)
    • The count of VMs running on that host (NumVM)
    1. Sort Cluster, Name: This part sorts the list first by cluster name and then by the ESXi host name, making it easier to review and analyze.
Elsewhere On TurboGeek:  PowerShell OneLiners: Automation Tips and Tricks

List all VM’s and their disk sizes

Effective disk management is essential in any virtualized environment. Having an accurate account of each Virtual Machine’s (VM) disk usage not only aids in monitoring but also in predictive activities like capacity planning.

Bash
ForEach ($VM in Get-VM ){($VM.Extensiondata.Guest.Disk | Select @{N="Name";E={$VM.Name}},DiskPath, @{N="Capacity(MB)";E={[math]::Round($_.Capacity/ 1MB)}}, @{N="Free Space(MB)";E={[math]::Round($_.FreeSpace / 1MB)}}, @{N="Free Space %";E={[math]::Round(((100* ($_.FreeSpace))/ ($_.Capacity)),0)}})}

Command Explanation

  • ForEach ($VM in Get-VM ){...}: The script starts by iterating over each VM retrieved by the Get-VM cmdlet.
    1. $VM.Extensiondata.Guest.Disk: Fetches disk-related details from the Guest property of each VM’s ExtensionData.
    2. Select @{N="Name";E={$VM.Name}},DiskPath, ...: This segment formats the output to display the following attributes:
    • VM Name (Name)
    • Disk Path (DiskPath)
    • Disk Capacity in MB (Capacity(MB))
    • Free Disk Space in MB (Free Space(MB))
    • Percentage of Free Space (Free Space %)

The expression [math]::Round($_.Capacity/ 1MB) is used to round off the disk capacity to the nearest MB. Similarly, [math]::Round($_.FreeSpace / 1MB) rounds off the available free space, and [math]::Round(((100* ($_.FreeSpace))/ ($_.Capacity)),0) calculates the percentage of free space.

After executing the command, you will receive a detailed list that includes each VM’s name, disk path, disk capacity in MB, free disk space in MB, and the percentage of free space.


Get Host Hardware information

Hardware metrics serve as crucial data points for the effective management and monitoring of ESXi hosts in a VMware environment. Detailed hardware information can help system administrators make informed decisions on capacity planning, performance tuning, and hardware maintenance.

Bash
Get-VMHost | Sort-Object Name | Get-View | Select-Object Name, @{N="Type";E={$_.Hardware.SystemInfo.Vendor + " " + $_.Hardware.SystemInfo.Model}}, @{N="CPU";E={"PROC: " + $_.Hardware.CpuInfo.NumCpuPackages + " CORES: " + $_.Hardware.CpuInfo.NumCpuCores + " MHZ: " + [math]::Round($_.Hardware.CpuInfo.Hz / 1000000, 0)}}, @{N="MEM";E={"" + [math]::Round($_.Hardware.MemorySize / 1GB, 0) + " GB"}}

Command Explanation

  • Get-VMHost | Sort-Object Name | Get-View | Select-Object Name, ...: This multi-part command pipeline fetches, sorts, and selects specific attributes related to the hardware of each ESXi host.
    1. Get-VMHost: Initiates the sequence by retrieving all ESXi hosts within your VMware setup.
    2. Sort-Object Name: Sorts the retrieved ESXi hosts alphabetically by name.
    3. Get-View: Retrieves the complete view of each ESXi host object, offering deeper details not immediately available through Get-VMHost.
    4. Select-Object Name, ...: This segment formats the output to show the following attributes:
    • Host Name (Name)
    • Hardware Type (Type), which includes Vendor and Model
    • CPU Configuration (CPU), including the number of processors, cores, and their speed in MHz
    • Memory Size in GB (MEM)

Specifically, [math]::Round($_.Hardware.CpuInfo.Hz / 1000000, 0) is used to convert the CPU frequency to MHz, and [math]::Round($_.Hardware.MemorySize / 1GB, 0) translates the memory size into GB.


Find VMs Created in the Last 10 Days

Tracking newly created Virtual Machines (VMs) is essential for maintaining security, compliance, and resource allocation in a VMware environment.

Bash
Get-VIEvent -maxsamples 10000 |where {$_.Gettype().Name-eq "VmCreatedEvent" -or $_.Gettype().Name-eq "VmBeingClonedEvent" -or $_.Gettype().Name-eq "VmBeingDeployedEvent"} |Sort CreatedTime -Descending |Select CreatedTime, UserName,FullformattedMessage -First 10

Command Explanation

  • Get-VIEvent -maxsamples 10000 | where {...} | Sort CreatedTime -Descending | Select CreatedTime, UserName, FullformattedMessage -First 10:
    1. Get-VIEvent -maxsamples 10000: This fetches up to 10,000 of the most recent events in the VMware environment.
    2. where {...}: Filters events to include only those where a VM was created, cloned, or deployed.
    3. Sort CreatedTime -Descending: Sorts the filtered events by their creation time, starting from the most recent.
    4. Select CreatedTime, UserName, FullformattedMessage -First 10: Selects relevant details of the first 10 events based on the sorting.#

Get Snapshot details of $esxihost and list name, vmname, sizegb and snapshot description

Snapshots provide a point-in-time representation of VMs, aiding in backup and recovery processes.

Bash
$esxihost | Get-VM | Get-Snapshot | Select VM,Name,Created,sizegb,description

Command Explanation

  • $esxihost | Get-VM | Get-Snapshot | Select VM,Name,Created,sizegb,description:
    • Fetches snapshot information of VMs on the $esxihost and selects details like VM name, snapshot name, creation time, size in GB, and snapshot description.

lists network adapter details

Knowing the network adapter configurations of your VMs is crucial for connectivity and troubleshooting.

Bash
$myvm | Get-NetworkAdapter | Select parent, name, type, networkname, connectionstate |Format-Table -AutoSize	Define $myvms 

Command Explanation

  • $myvm | Get-NetworkAdapter | Select parent, name, type, networkname, connectionstate | Format-Table -AutoSize:
    • Retrieves the network adapter details for $myvm and formats them into an auto-sized table. The table includes details like the parent object (usually the VM name), adapter name, type, network name, and connection state.

Richard.Bailey

Richard Bailey, a seasoned tech enthusiast, combines a passion for innovation with a knack for simplifying complex concepts. With over a decade in the industry, he's pioneered transformative solutions, blending creativity with technical prowess. An avid writer, Richard's articles resonate with readers, offering insightful perspectives that bridge the gap between technology and everyday life. His commitment to excellence and tireless pursuit of knowledge continues to inspire and shape the tech landscape.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »