VMware Arena

PowerCLI Script: Retrieve Cluster Name and Datastore Name of Virtual Machines

Most of the time, we all be excited to create or run the PowerCLI Script to accomplish the tasks within a short period of time by eliminating a lot of manual processes. Similarly, I was working on one of the tasks where I need to retrieve the cluster name and datastore name for some of the clustered virtual machines. So in this case, I have virtual machine names but I need to identify in which cluster this virtual machine is running and also in which datastore these VM’s are stored. I wrote a simple powerCLI script to read the VM names from the text file and provide the respective cluster name and datastore names in the excel sheet. you can also add other details to retrieve for the virtual machine along with cluster name and datastore name. I know this is a simple script but sometimes this may save a lot of our time and effort.

 

If(!(Get-PSSnapin | Where {$_.Name -Eq "VMware.VimAutomation.Core"}))
{
	Add-PSSnapin VMware.VimAutomation.Core
}

$VCServer = Read-Host 'Enter VC Server name'
$vcUSERNAME = Read-Host 'Enter user name'
$vcPassword = Read-Host 'Enter password' -AsSecureString
$vccredential = New-Object System.Management.Automation.PSCredential ($vcusername, $vcPassword)

Write-Host "Connecting to $VCServer..." -Foregroundcolor "Yellow" -NoNewLine
$connection = Connect-VIServer -Server $VCServer -Cred $vccredential -ErrorAction SilentlyContinue -WarningAction 0 | Out-Null
$Global:Report = @()

$VMS = Get-Content "vmname.txt"
$Results = @()
Foreach($VM in $VMS)
{
	Write-Host "Checking $VM...." -NoNewLine 
	$Result = Get-VM $VM | Select Name, @{N="Cluster";E={Get-Cluster -VM $_}},@{N="Datastore";E={Get-Datastore -VM $_}}
	Write-Host "Completed"
	$Results += $Result
}

$Results | Export-CSV -NoTypeInformation vmdetails.csv 
Disconnect-VIServer -server $VCServer

How to Execute the Script?

Copy and Paste the above script and save it in the Notepad. Name the script as “vminfo.ps1″

  1. Execute the Script in PowerCLI “.\vminfo.ps1
  2. Input  vCenter Server Name to execute the script to get the report
  3. Enter the Username with administrative credentials on vCenter Server
  4. Enter the password for the above-entered Username
  5. Hit Enter to execute the script and pull the report.

Script Output

virtual machine along with cluster name and Datastore will be exported and saved in the Microsoft Excel output file with the filename “vmdetails.CSV” under the same directory where the PowerCLI Script “vminfo.ps1”  is located.

 

I hope the script will be useful for you to save a lot of time and avoid manual works. Thanks for Reading !!! Be social and share it on social media, if you feel worth sharing it.

Exit mobile version