PowerCLI – Get a List of VMs from a List of Datastores

I’ve found plenty of examples for pulling a list of VMs from a Datastore in PowerCLI. The requirement was given a list of LUNs, which Datastores did not contain VMs. Running the script for each Datastore would not have been any faster than browsing each datastore in the GUI.

I have a programming background from college, and found the learning curve with Powershell to be steep. Adding PowerCLI into the mix immediately upon diving in did not help. Some documentation and script examples are already obsolete from depreciated Cmdlets and Cmdlet options in PowerCLI; specifically, the Get-Datastore Cmdlet frequently returned this error “Passing values to this parameter through a pipeline is deprecated  and will be removed in a future release.” The website http://psvmware.wordpress.com/tag/get-vms-that-reside-on-datastore/ provided an essential piece of code but I could not pass an array of values directly into the Get-Datastore Cmdlet via a pipe “|” : 

 

Get-Content “TextFile” | (Get-Datastore -Name ‘datastore_name’).Extensiondata.Vm|%{(Get-View -Id $_.toString()).name}

 

I used a ForEach loop to pull the Datastore names out of the file one at time and pass each one individuallly to the Get-Datastore Cmdlet. Here is my modification in full:

 

$Result = ForEach ($Datastore in (Get-Content $ListofDatastores)) { 

(Get-Datastore -Name $Datastore).Extensiondata.Vm|%{(Get-View -Id $_.toString()).name}}
Echo $Result

 

Here is the entire script. It will request all required information to connect to vCenter, produce the desired output, and save the output to a text file.

<#
This Script will take a text file of line separated Datastores and output the VMs they contain.
#>

Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage=”vCenter Server?”)]
[string] $vCenter,
[Parameter(Mandatory=$true, Position=0, HelpMessage=”User DOMAIN\USER”)]
[string] $UserName,
[Parameter(Mandatory=$true, Position=0, HelpMessage=”Password?”)]
[Security.SecureString] $Password,
[Parameter(Mandatory=$true, Position=0, HelpMessage=”Enter .txt File Name of the List of Datastores”)]
[string] $ListofDatastores
)

$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

Connect-VIServer -Server $vCenter -User $UserName -Password $pw

$Result = ForEach ($Datastore in (Get-Content $ListofDatastores)) { 
Echo “”
Echo $Datastore
Echo “”
(Get-Datastore -Name $Datastore).Extensiondata.Vm|%{(Get-View -Id $_.toString()).name}}
Echo $Result
Echo “”
Echo $Result | Out-File VMsOnDatastore.txt
Echo “Results stored in VMsOnDatastore.txt”