{"id":1227,"date":"2024-01-28T13:48:35","date_gmt":"2024-01-28T12:48:35","guid":{"rendered":"https:\/\/myitdailydose.com\/?p=1227"},"modified":"2024-01-28T20:15:57","modified_gmt":"2024-01-28T19:15:57","slug":"retrieving-vm-information-with-powershell-and-vmware-powercli","status":"publish","type":"post","link":"https:\/\/myitdailydose.com\/index.php\/2024\/01\/28\/retrieving-vm-information-with-powershell-and-vmware-powercli\/","title":{"rendered":"Retrieving VM Network Settings with PowerShell and PowerCLI"},"content":{"rendered":"<p>Recently, one of my clients requested information about virtual machines (VMs) such as IP address, subnet mask, and default gateway for a specific VLAN. To streamline the process, I decided to create a quick PowerShell script using the VMware.PowerCLI module.<\/p>\n<h2>What is VMware.PowerCLI?<\/h2>\n<p>VMware.PowerCLI is a powerful command-line interface (CLI) tool that allows you to manage and automate VMware vSphere environments using PowerShell. It provides a wide range of cmdlets specifically designed for managing VMware infrastructure, making it an ideal choice for automating repetitive tasks.<\/p>\n<h2>Getting Started with VMware.PowerCLI<\/h2>\n<p>To begin, you&#8217;ll need to install the VMware.PowerCLI module. Open a PowerShell console with administrative privileges and run the following command:<\/p>\n<pre>Install-Module -Name VMware.PowerCLI -Scope CurrentUser<\/pre>\n<p>This command will download and install the latest version of the VMware.PowerCLI module from the PowerShell Gallery.<\/p>\n<p>you can install VMware.PowerCLI on a computer that is not connected to the internet by manually downloading the PowerCLI module from the internet-connected machine and then transferring it to the offline machine by using this <a href=\"_wp_link_placeholder\" data-wplink-edit=\"true\">methode<\/a>.<\/p>\n<h2>Connecting to the VMware vSphere Environment<\/h2>\n<p>Once the module is installed, you can connect to your VMware vSphere environment using the <code>Connect-VIServer<\/code> cmdlet. This cmdlet requires the IP address or hostname of your vCenter Server and your credentials.<\/p>\n<pre>Connect-VIServer -Server &lt;vCenterServer&gt; -User &lt;Username&gt; -Password &lt;Password&gt;<\/pre>\n<p>Replace &lt;vCenterServer&gt;, &lt;Username&gt;, and &lt;Password&gt; with the appropriate values for your environment.<\/p>\n<h2>Retrieving VM Information<\/h2>\n<p>With the VMware.PowerCLI module connected to your vSphere environment, you can now retrieve the required information for the specific VLAN. The following PowerShell script demonstrates how to retrieve the IP address, subnet mask, and default gateway for VMs on a particular VLAN:<\/p>\n<pre>$PG_VLANID = \"123\" # Replace with the VLAN ID you want to query\n\n# Getting PortGroup Name\n$PG_NAME = Get-VDPortgroup | ForEach-Object {if (($_.VlanConfiguration).VlanId -eq $PG_VLANID){ $_.Name }}\n\nWrite-Host \"PortGroup Name is $PG_NAME\"\n\n# Getting all VMs attached to the specified PortGroup\n$VMs = Get-VirtualPortGroup -Name $PG_NAME | Get-VM | Select-Object -ExpandProperty Name\nWrite-Host \"Number of VMs attached to this PortGroup is $($VMs.count)\"\n\nforeach($VM in $VMs){\n\nWrite-Host \"---------------- $VM ----------------\"\nWrite-Host \" VM Name: $VM\"\n$VM_detail = Get-VM -Name $VM\n\n# check the status of the VM &amp; VM Tools.\n\nif (($VM_detail.PowerState -eq \"PoweredOn\") -and (($VM_detail.Guest).State -eq \"Running\")){\nWrite-Host \" VM is $($VM_detail.PowerState).\"\nWrite-Host \" VM Tools is $(($VM_detail.Guest).State).\"\n$VM_OS = $VM_detail.Guest.OSFullName\n$VM_IP = $VM_detail.Guest.IPAddress[0]\n$VM_MASK = $VM_detail.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | where {$_.Network -eq \"$($VM_IP.Substring(0,$VM_IP.LastIndexOf(\".\"))).0\"} | select -ExpandProperty PrefixLength\n$VM_GATEWAY = $VM_detail.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute.Gateway.IpAddress | where {$_ -ne $null}\n$VM_DNS = [string]::Join(',',($VM_detail.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))\nWrite-Host \" OS: $VM_OS\"\nWrite-Host \" IP Address: $VM_IP\"\nWrite-Host \" MASK: $VM_MASK\"\nWrite-Host \" Default Gateway: $VM_GATEWAY\"\nWrite-Host \" DNS: $VM_DNS\"\n\n}\nelse {\nWrite-Host \" VM is $($VM_detail.PowerState).\"\nWrite-Host \" VM Tools is $(($VM_detail.Guest).State).\"\n$VM_OS = $VM_detail.Guest.OSFullName\nWrite-Host \" OS: $VM_OS\"\nWrite-Host \" IP Address: N\/A\"\nWrite-Host \" MASK: N\/A\"\nWrite-Host \" Default Gateway: N\/A\"\nWrite-Host \" DNS: N\/A\"\n\n}\n\nWrite-Host \"--------------------------------------------\"\n<\/pre>\n<p>Make sure to replace &#8220;123&#8221; in the <code>$PG_VLANID<\/code> variable with the actual VLAN ID you want to query. This script retrieves all VMs connected to the specified VLAN and displays their respective IP address, subnet mask, and default gateway.<\/p>\n<h2>Final Script<\/h2>\n<p>Here is the script that i created for my client to achieve this task. The script automates the process and generates a CSV result file named &#8216;VMs_VlanID.csv,&#8217; streamlining data output for efficient analysis and reference.<\/p>\n<pre>&lt;#\n===========================================================================\nScript Name: Get-VM-Netwrork-Settings\nVersion: 0.1\nModified on: 23.01.2023\nCreated by: Abdelilah BAKIR\n===========================================================================\n#&gt;\n\n\nparam ([Parameter(Mandatory)]$VcenterServer)\n\nif ( -Not (Test-Path -Path .\\Logs)){\nWrite-Host \"$(Get-Date -Format G) : Creating Logs Folder..\" -ForegroundColor Green\nNew-Item -Name Logs -ItemType Directory -Force -ErrorAction Stop\n\n}\n\n$logpath = \"Logs\\$(get-date -format s | foreach {$_ -replace \":\", \".\"}).log\"\n\nfunction Write-Log\n{\n\tparam($msg,$color)\n    \n    if ($color -eq \"Red\"){\n    \n     Write-host \"$(Get-Date -Format G) : $msg\" -ForegroundColor Red\n\n    }\n    elseif ($color -eq \"Green\") {\n    \n    Write-host \"$(Get-Date -Format G) : $msg\" -ForegroundColor Green\n\n    \n    }else {\n    \n    Write-host \"$(Get-Date -Format G) : $msg\"\n    \n    }\n      \n\n\t\"$(Get-Date -Format G) : $msg\" | Out-File -FilePath $logpath -Append -Force\n}\n\n\nif ([string]::IsNullOrEmpty($(Get-Module -Name VMware.PowerCLI -ListAvailable))) {\n\nWrite-Log \"VMware.PowerCLI module is not Installed.\" -color Red\n$Installation_Choice = Read-Host \"Do you Want to install it. (Y\/N)\"\nswitch ($Installation_Choice.Trim())\n{\n    \"y\"\n    {\n    Write-Log \"Starting Instalaltion of VMware.PowerCLI module.\" -color Green\n    \n    try\n        {\n        Install-Module VMware.PowerCLI -Force\n      }\n    catch \n       {\n      \n       $ErrorMessage = $_.Exception.Message\n       Write-Log \"$ErrorMessage\" -color Red\n       Start-Sleep -Seconds 120\n       exit 1\n    }\n\n\n\n        }\n    \"n\" { \n    Write-Log \"Instalaltion aborted. Exiting in 1 minutes.\" -color Red\n    Start-Sleep -Seconds 60\n    Exit 1\n    }\n\n  }\n\n}\n\nif ($Authenticated -ne $True){\n\nSet-PowerCLIConfiguration -InvalidCertificateAction Ignore -ParticipateInCeip $false -Confirm:$false\n\ndo\n{\n try\n        {\n        $MyCredentials = Get-Credential\n      }\n    catch \n       {\n      \n       $ErrorMessage = $_.Exception.Message\n       Write-Log \"$ErrorMessage\" -color Red\n       Write-Log \"Exiting in 1 minutes.\" -color Red\n       Start-Sleep -Seconds 120\n       exit 1\n    }\n\n\n  if (Connect-VIServer -server $VcenterServer -Credential $MyCredentials -ErrorAction SilentlyContinue){\n  Write-Log \"Authentication success. Go to the next step...\" -color Green\n  $Authenticated = $true\n   }\n   else{\n \n  $Authenticated = $false\n  Write-Log \"Something went wrong, Try again please.\" -color Red\n\n  }\n\n}\nwhile ($Authenticated -eq $false)\n\n}\n\n\n$PG_VLANID = (Read-Host \"Enter the VLAN ID\").Trim()\n\ntry\n{\n    $PG_NAME = Get-VDPortgroup | ForEach-Object {if (($_.VlanConfiguration).VlanId -eq $PG_VLANID){ $_.Name }}\n    if ( [string]::IsNullOrEmpty($PG_NAME)){\n    Write-Log \"VLAN ID $PG_VLANID is not Exist.\" -color Red\n    Write-Log \"Exiting in 2 minutes.\" -color Red\n    Start-Sleep -Seconds 120\n    Exit 1\n    }\n\n    Write-Log \"PortGroup Name is $PG_NAME\" -color Green\n\n\n    $VMs = Get-VirtualPortGroup -Name $PG_NAME | Get-VM | Select-Object -ExpandProperty Name  \n\n    if ( [string]::IsNullOrEmpty($($VMs))){\n    Write-Log \"No VM attached to Vlan ID $PG_VLANID.\" -color Red\n    Write-Log \"Exiting in 2 minutes.\" -color Red\n    Start-Sleep -Seconds 120\n    Exit 1\n    }\n\n    Write-Log \"Number of VMs attached to this PortGroup is $($VMs.count) \" -color Green\n\n    $ResulFileName = \"VMs_$PG_VLANID.csv\"\n\n    \"VM Name;VM Status;VM Tools;OS;IP Address; MASK;Default Gateway;DNS\" | Out-File -FilePath $ResulFileName -force\n}\ncatch \n{\n    $ErrorMessage = $_.Exception.Message\n    $FailedItem = $_.Exception.ItemName\n    Write-Log \"$ErrorMessage\" -color Red\n    Start-Sleep -Seconds 120\n    exit 1\n}\n\n\nforeach($VM in $VMs){\n\nWrite-Log \"---------------- $VM ----------------\"\nWrite-Log \" VM Name: $VM\"\n$VM_detail = Get-VM -Name $VM\n\nif (($VM_detail.PowerState -eq \"PoweredOn\") -and (($VM_detail.Guest).State -eq \"Running\")){\n    Write-Log \" VM is $($VM_detail.PowerState).\"\n    Write-Log \" VM Tools is $(($VM_detail.Guest).State).\"\n    $VM_OS = $VM_detail.Guest.OSFullName\n    $VM_IP = $VM_detail.Guest.IPAddress[0]\n    $VM_MASK = $VM_detail.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | where {$_.Network -eq \"$($VM_IP.Substring(0,$VM_IP.LastIndexOf(\".\"))).0\"} | select -ExpandProperty PrefixLength\n    $VM_GATEWAY = $VM_detail.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute.Gateway.IpAddress | where {$_ -ne $null}\n    $VM_DNS = [string]::Join(',',($VM_detail.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))\n    Write-Log \" OS: $VM_OS\"\n    Write-Log \" IP Address: $VM_IP\"\n    Write-Log \" MASK: $VM_MASK\"\n    Write-Log \" Default Gateway: $VM_GATEWAY\"\n    Write-Log \" DNS: $VM_DNS\"\n\n    \"$VM;$($VM_detail.PowerState);$(($VM_detail.Guest).State);$VM_OS;$VM_IP;$VM_MASK;$VM_GATEWAY;$VM_DNS\" | Out-File -FilePath $ResulFileName -Append\n\n}else {\n    Write-Log \" VM is $($VM_detail.PowerState).\"\n    Write-Log \" VM Tools is $(($VM_detail.Guest).State).\"\n    $VM_OS = $VM_detail.Guest.OSFullName\n    Write-Log \" OS: $VM_OS\"\n    Write-Log \" IP Address: N\/A\"\n    Write-Log \" MASK: N\/A\"\n    Write-Log \" Default Gateway: N\/A\"\n    Write-Log \" DNS: N\/A\"\n\n    \"$VM;$($VM_detail.PowerState);$(($VM_detail.Guest).State);$VM_OS;N\/A;N\/A;N\/A;N\/A\" | Out-File -FilePath $ResulFileName -Append\n\n}\n\n\nWrite-Log \"--------------------------------------------\"\n\n\n}\n\nWrite-Log \"Please check the Result file $ResulFileName\" -color Green<\/pre>\n<p>Save the script with a .ps1 file extension (e.g., <code>get-vm-info.ps1<\/code>) and run it from a PowerShell console. Ensure that you have the appropriate permissions to access the vSphere environment.<\/p>\n<h2>Wrapping Up<\/h2>\n<p>Using the VMware.PowerCLI module, you can quickly retrieve VM information such as IP address, subnet mask, and default gateway for a specific VLAN. By automating this process with PowerShell, you can save time and effort, especially when dealing with large-scale VMware environments.<\/p>\n<p>Remember to always test your scripts in a non-production environment before running them in a production environment. This ensures that you are familiar with the script&#8217;s behavior and prevents any unintended consequences.<\/p>\n<p>I trust this article was beneficial for you. If there\u2019s anything you\u2019d like to discuss or inquire about, please don\u2019t hesitate to leave a comment below.<\/p>\n<p>Thank you for being part of our community. Let\u2019s explore, learn, and grow together at MyITDailyDose.com.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Recently, one of my clients requested information about virtual machines (VMs) such as IP address, subnet mask, and default gateway for a specific VLAN. To streamline the process, I decided to create a quick PowerShell script using the VMware.PowerCLI module. What is VMware.PowerCLI? VMware.PowerCLI is a powerful command-line interface (CLI) tool that allows you to &hellip;<\/p>\n","protected":false},"author":3,"featured_media":905,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[14],"tags":[31,43,42],"class_list":["post-1227","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-powershell","tag-powershell","tag-vmware-vsphere","tag-vmware-powercli"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/posts\/1227","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/comments?post=1227"}],"version-history":[{"count":16,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/posts\/1227\/revisions"}],"predecessor-version":[{"id":1258,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/posts\/1227\/revisions\/1258"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/media\/905"}],"wp:attachment":[{"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/media?parent=1227"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/categories?post=1227"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/myitdailydose.com\/index.php\/wp-json\/wp\/v2\/tags?post=1227"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}