--- title: "Using PowerCLI to list Linux VMs and Datacenter Locations" # Title of the blog post. date: 2022-01-13T13:53:08-06:00 # Date of post creation. # lastmod: 2022-01-13T13:53:08-06:00 # Date when last modified description: "A quick bit of PowerCLI to generate a report showing Linux VMs and their datacenter locations." # Description used for search engine. featured: false # Sets if post is a featured post, making appear on the home page side bar. draft: false # Sets whether to render this page. Draft of true will not be rendered. toc: false # Controls if a table of contents should be generated for first-level links automatically. usePageBundles: true # menu: main # featureImage: "file.png" # Sets featured image on blog post. # featureImageAlt: 'Description of image' # Alternative text for featured image. # featureImageCap: 'This is the featured image.' # Caption (optional). thumbnail: "PowerCLI.png" # Sets thumbnail image appearing inside card on homepage. # shareImage: "share.png" # Designate a separate image for social media sharing. codeLineNumbers: false # Override global value for showing of line numbers within code block. categories: Code tags: - vmware - powercli - powershell comments: true # Disable comment if false. --- I recently needed to export a list of all the Linux VMs in a rather large vSphere environment spanning multiple vCenters (and the entire globe), and I wanted to include information about which virtual datacenter each VM lived in to make it easier to map VMs to their physical location. I've got a [`Connect-vCenters` function](/logging-in-to-multiple-vcenter-servers-at-once-with-powercli/) that I use to quickly log into multiple vCenters at once. That then enables me to run a single query across the entire landscape - but what query? There isn't really a direct way to get datacenter information out of the results generated by `Get-VM`; I could run an additional `Get-Datacenter` query against each returned VM object but that doesn't sound very efficient. What I came up with is using `Get-Datacenter` to enumerate each virtual datacenter, and then list the VMs matching my query within: ```powershell # torchlight! {"lineNumbers": true} $linuxVms = foreach( $datacenter in ( Get-Datacenter )) { Get-Datacenter $datacenter | Get-VM | Where { $_.ExtensionData.Config.GuestFullName -notmatch "win" -and $_.Name -notmatch "vcls" } | ` Select @{ N="Datacenter";E={ $datacenter.Name }}, Name, Notes, @{ N="Configured OS";E={ $_.ExtensionData.Config.GuestFullName }}, # OS based on the .vmx configuration @{ N="Running OS";E={ $_.Guest.OsFullName }}, # OS as reported by VMware Tools @{ N="Powered On";E={ $_.PowerState -eq "PoweredOn" }}, @{ N="IP Address";E={ $_.ExtensionData.Guest.IpAddress }} } $linuxVms | Export-Csv -Path ./linuxVms.csv -NoTypeInformation -UseCulture ``` This gave me a CSV export with exactly the data I needed.