Skip to content

Instantly share code, notes, and snippets.

@schbrongx
Created April 4, 2023 15:01
Show Gist options
  • Save schbrongx/3c8ab894d94925a73db952bf4e8d5eda to your computer and use it in GitHub Desktop.
Save schbrongx/3c8ab894d94925a73db952bf4e8d5eda to your computer and use it in GitHub Desktop.
PS1: Connect to vSphere, fetch VMs, output grouped by OS: Linux, Windows and Others
if (Get-Module -ListAvailable -Name VMware.PowerCLI) {
Import-Module VMWare.PowerCLI
}
else {
try {
Install-Module -Name VMware.PowerCLI
}
catch {
exit 1
}
}
# Set PowerCLI configuration to ignore invalid certificates
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
# Connect to vSphere server
$server = ""
$username = ""
$password = ""
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $securePassword)
Connect-VIServer -Server $server -Credential $credential
# Fetch list of VMs and group them by OS
$vms = Get-VM | Select Name, @{N='GuestOS'; E={$_.Guest.OSFullName}}
$linuxGroup = $vms | Where-Object {$_.GuestOS -like "*Linux*"} | Format-Table -AutoSize
$windowsGroup = $vms | Where-Object {$_.GuestOS -like "*Windows*"} | Format-Table -AutoSize
$otherGroup = $vms | Where-Object {($_.GuestOS -notlike "*Linux*") -and ($_.GuestOS -notlike "*Windows*")} | Format-Table -AutoSize
# Display VMs in tables grouped by OS
Write-Host "Linux VMs:`n"
$linuxGroup
Write-Host "`nWindows VMs:`n"
$windowsGroup
Write-Host "`nOther VMs:`n"
$otherGroup
# Disconnect from vSphere server
Disconnect-VIServer -Server $server -Confirm:$false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment