1. Install VMware PowerCLI: If not already installed, you need to install VMware’s PowerCLI. This can be done by running the following command in an elevated PowerShell session:
Install-Module -Name VMware.PowerCLI
2. Configure PowerCLI Settings: To avoid certificate errors when connecting to the ESXi host, you might need to configure PowerCLI to ignore invalid or self-signed certificates. This can be done by running:
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
3. Connect to the ESXi Host: Use the Connect-VIServer cmdlet to establish a connection to your ESXi host. Replace <ESXiHostNameOrIPAddress> with your actual ESXi host name or IP address, and provide the credentials when prompted:
Connect-VIServer -Server <ESXiHostNameOrIPAddress>
4. Retrieve VM Information: Once connected, you can retrieve a list of all VMs hosted on the ESXi server along with their desired properties using the Get-VM cmdlet. For illustration, we’ll fetch a basic set of properties such as Name, VMHost, PowerState, and NumberOfCpus. You can adjust the properties according to your requirements:
- Option 1: $vmList = Get-VM | Select-Object Name, VMHost, PowerState, NumberOfCpus, MemoryGB
- Option 2: $vmList = Get-VM | Select-Object Name, PowerState, Notes, Guest, NumCpu, CoresPerSocket, MemoryMB, MemoryGB, VMHostId, VMHost, VApp, FolderId, Folder, ResourcePoolId, ResourcePool, HARestartPriority, HAIsolationResponse, DrsAutomationLevel, VMSwapfilePolicy, VMResourceConfiguration, Version, HardwareVersion, PersistentId, GuestId, @{Name='UsedSpaceGB'; Expression={[math]::Round($_.UsedSpaceGB, 2)}}, @{Name='ProvisionedSpaceGB'; Expression={[math]::Round($_.ProvisionedSpaceGB, 2)}}, @{Name='DatastoreIdList'; Expression={($_.DatastoreIdList -join ',')}}, CreateDate, SEVEnabled, BootDelayMillisecond, MigrationEncryption, MemoryHotAddEnabled, MemoryHotAddIncrement, MemoryHotAddLimit, CpuHotAddEnabled, CpuHotRemoveEnabled, @{Name='ExtensionData'; Expression={$_ | Select-Object -ExpandProperty ExtensionData | ConvertTo-Json -Depth 10}}, @{Name='CustomFields'; Expression={($_.CustomFields | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join '; '}}, Id, Uid
5. Export to CSV File: With the list of VMs and their properties stored in $vmList, you can now export this information to a CSV file. Specify your desired path and filename for the CSV file in place of <PathToYourCSVFile>:
$vmList | Export-Csv -Path <PathToYourCSVFile> -NoTypeInformation
6. Disconnect from the ESXi Host: After exporting the VM list to a CSV file, cleanly disconnect from the ESXi host to end your session:
Disconnect-VIServer -Server <ESXiHostNameOrIPAddress> -Confirm:$false
VÕ TÌNH THƯƠNG
[email protected]