vSphere Admin scripts

Some scripts that I use to manage vSphere

Turn off SSH if running

# Connect to the vCenter Server
Connect-VIServer -Server <vCenterServer> -User <Username> -Password <Password>

# Stop SSH service on all ESXi hosts where it is running
Get-VMHost | Get-VMHostService | Where-Object { $_.Key -eq "TSM-SSH" -and $_.Running -eq $true } | Stop-VMHostService -Confirm:$false

# Disconnect from the vCenter Server
Disconnect-VIServer -Confirm:$false

Count the number of VMs that are in each vSphere cluster

# Connect to the vCenter Server
Connect-VIServer -Server <vCenterServer> -User <Username> -Password <Password>

# Initialize an empty array for results
$ClusterVMCounts = @()

# Get all clusters in the vCenter
$Clusters = Get-Cluster

# Loop through each cluster
foreach ($Cluster in $Clusters) {
    # Get all VMs in the cluster
    $VMs = Get-VM -Location $Cluster
    
    # Count the number of running VMs
    $RunningVMs = $VMs | Where-Object { $_.PowerState -eq "PoweredOn" } | Measure-Object
    
    # Add the cluster and count to the results array
    $ClusterVMCounts += [PSCustomObject]@{
        ClusterName = $Cluster.Name
        RunningVMs = $RunningVMs.Count
    }
}

# Display the results
$ClusterVMCounts | Format-Table -AutoSize

# Disconnect from the vCenter Server
Disconnect-VIServer -Confirm:$false

List the 10 largest VMs per cluster

Per RAM

# Connect to vCenter
Connect-VIServer -Server "vCenter_Server_Name" -User "username" -Password "password"

# Retrieve all clusters
$clusters = Get-Cluster

# Loop through each cluster and retrieve the top 10 largest VMs based on virtual cores
foreach ($cluster in $clusters) {
    Write-Host "Cluster: $($cluster.Name)" -ForegroundColor Green
    
    # Get all VMs in the cluster
    $vms = Get-VM -Location $cluster | Select Name, NumCpu, MemoryGB
    
    # Sort VMs by number of virtual cores (NumCpu) in descending order
    $sortedVMs = $vms | Sort-Object -Property NumCpu -Descending
    
    # Select the top 10 VMs
    $topVMs = $sortedVMs | Select-Object -First 10
    
    # Display the VM details
    $topVMs | Format-Table -AutoSize
    Write-Host "`n" # Add a line break for readability
}

# Disconnect from vCenter
Disconnect-VIServer -Confirm:$false

Example output

Cluster: Cluster1
Name        NumCpu    MemoryGB
----        ------    --------
VM1         16        64
VM2         12        32
VM3         10        48
...

Cluster: Cluster2
Name        NumCpu    MemoryGB
----        ------    --------
VM4         20        128
VM5         16        64
VM6         12        32
...

Export to CSV as well

$report = @()
foreach ($cluster in $clusters) {
    $topVMs = Get-VM -Location $cluster | Sort-Object -Property NumCpu -Descending | Select-Object -First 10
    $topVMs | ForEach-Object {
        $report += [PSCustomObject]@{
            Cluster   = $cluster.Name
            VMName    = $_.Name
            NumCpu    = $_.NumCpu
            MemoryGB  = $_.MemoryGB
        }
    }
}

# Export the report to a CSV file
$report | Export-Csv -Path "C:\TopVMsByCluster.csv" -NoTypeInformation

Users logged into vCenter

# Connect to vCenter
Connect-VIServer -Server "vCenter_Server_Name" -User "username" -Password "password"

# Get the ServiceInstance and SessionManager
$serviceInstance = Get-View ServiceInstance
$sessionManager = Get-View $serviceInstance.Content.SessionManager

# Get current time
$now = Get-Date

# Create a report for logged-in users
$loggedInUsers = @()
foreach ($session in $sessionManager.SessionList) {
    # Calculate idle time
    $idleTime = $now - $session.LastActiveTime
    $formattedIdleTime = '{0:00}:{1:00}:{2:00}' -f $idleTime.Hours, $idleTime.Minutes, $idleTime.Seconds

    # Add user session details to the report
    $loggedInUsers += [PSCustomObject]@{
        UserName   = $session.UserName
        LoginTime  = $session.LoginTime
        IdleTime   = $formattedIdleTime
    }
}

# Display the logged-in users
$loggedInUsers | Format-Table -AutoSize

# Disconnect from vCenter
Disconnect-VIServer -Confirm:$false

example output

UserName          LoginTime               IdleTime
--------          ---------               --------
admin             10/25/2023 10:00:00 AM  00:30:15
user1             10/25/2023 9:45:00 AM   01:15:45
user2             10/25/2023 8:20:00 AM   02:40:30

Disconnect idle users

# Connect to vCenter
Connect-VIServer -Server "vCenter_Server_Name" -User "username" -Password "password"

# Define the idle time threshold (in minutes)
$IdleTimeThresholdMinutes = 30

# Get the ServiceInstance and SessionManager
$serviceInstance = Get-View ServiceInstance
$sessionManager = Get-View $serviceInstance.Content.SessionManager

# Get current time
$now = Get-Date

# Loop through each session and disconnect idle ones
foreach ($session in $sessionManager.SessionList) {
    # Calculate idle time in minutes
    $idleTimeMinutes = ($now - $session.LastActiveTime).TotalMinutes

    # Check if the idle time exceeds the threshold
    if ($idleTimeMinutes -ge $IdleTimeThresholdMinutes) {
        Write-Host "Disconnecting session for user: $($session.UserName) (Idle Time: $idleTimeMinutes minutes)" -ForegroundColor Yellow
        
        # Terminate the session
        $sessionManager.TerminateSession($session.Key)
    }
}

Write-Host "Idle sessions exceeding $IdleTimeThresholdMinutes minutes have been disconnected." -ForegroundColor Green

# Disconnect from vCenter
Disconnect-VIServer -Confirm:$false

Idle Time Threshold: The script uses $IdleTimeThresholdMinutes to define the maximum allowed idle time (e.g., 30 minutes). You can adjust this value as needed.

SessionManager.SessionList: Retrieves all active sessions from vCenter.

Idle Time Calculation: Calculates the idle time for each session using the LastActiveTime property.

Sample output

Disconnecting session for user: admin (Idle Time: 45 minutes)
Disconnecting session for user: user1 (Idle Time: 60 minutes)
Idle sessions exceeding 30 minutes have been disconnected.

    List VMs with Snapshots

    # Connect to vCenter
    Connect-VIServer -Server "vCenter_Server_Name" -User "username" -Password "password"
    
    # Initialize an array to store snapshot details
    $report = @()
    
    # Retrieve all VMs
    $vms = Get-VM
    
    # Loop through each VM and check for snapshots
    foreach ($vm in $vms) {
        $snapshots = Get-Snapshot -VM $vm -ErrorAction SilentlyContinue
        if ($snapshots) {
            foreach ($snapshot in $snapshots) {
                # Add snapshot details to the report
                $report += [PSCustomObject]@{
                    VMName       = $vm.Name
                    SnapshotName = $snapshot.Name
                    CreatedOn    = $snapshot.Created
                    Description  = $snapshot.Description
                }
            }
        }
    }
    
    # Display the report
    $report | Format-Table -AutoSize
    
    # Optionally, export the report to a CSV file
    $report | Export-Csv -Path "C:\VMsWithSnapshots.csv" -NoTypeInformation
    
    # Disconnect from vCenter
    Disconnect-VIServer -Confirm:$false

    Get-VM: Retrieves all virtual machines in the vCenter.
    Get-Snapshot -VM $vm: Retrieves snapshots for a specific VM. The -ErrorAction SilentlyContinue ensures the script does not throw errors if a VM has no snapshots.
    CreatedOn: Displays the creation date of the snapshot.
    Description: Displays the snapshot description (if available).
    Export-Csv: Saves the snapshot details to a CSV file for reporting purposes.

      Example output

      VMName       SnapshotName     CreatedOn               Description
      ------       ------------     ---------               -----------
      VM1          Snapshot1        10/20/2023 10:00:00 AM  Backup snapshot
      VM2          Snapshot2        10/15/2023 5:30:00 PM   Test snapshot
      VM3          Snapshot3        10/10/2023 2:45:00 PM   Pre-upgrade snapshot

      Leave a Reply

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

      Share on Social Media