This has been driving me batty for hours now and I have not gotten anywhere with it. I have a list of datastores which I want to extract a list of all VM names from and export the list to CSV.
Here's what I have:
Datastore Names are in a CSV file called "_SYD_Datastore_Names.csv"
Data format is:
Extracted volume name
DS1_t1_SYD_vmdata_0004
DS2_t1_SYD_vmdata_0017
DS3_t1_SYD_vmdata_0024
The output of the code is a separate CSV file per datastore which strangely contains the following data:
"Length"
"23"
Here are the values of my variables:
$DatastoreName
Value = DS1_t1_SYD_vmdata_0004
BaseType = System.Object
$oDatastore
Value =
Name FreeSpaceGB CapacityGB
---- ----------- ----------
DS1_t1_SYD_vmdata_0004 467.628 500.000
BaseType = VMware.VimAutomation.ViCore.Impl.V1.DatastoreManagement.DatastoreImpl
$VMList
Value = DS1_t1_SYD_vmdata_0004
BaseType = System.Array
My code:
#
# This function shows the Open File dialog to the user so the user can
# select the import CSV file.
#
Function Get-FileName($InitialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv) | *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.FileName
}
# Calling the function:
# -----------------------------------------------------------
# Get the CSV import file name and path:
$ImportCSVFile = Get-FileName
# Check if the user cancelled the request.
if ($ImportCSVFile -eq "")
{ # They did!
Throw "No file selected. Ending script"
}
# Load the file contents
# Time to get going!
$VMData = Import-CSV $ImportCSVFile -ErrorAction SilentlyContinue
ForEach( $Datastore in $VMData)
{
Try
{
$DatastoreName = ($Datastore | Select -expandproperty "Extracted volume name")
$oDatastore = Get-Datastore -Name $DatastoreName
$VMList = Get-VM -Datastore $oDatastore
}
Catch
{
$VMList = "Datastore Not Found"
}
Finally
{
$FileName1 = "DS_" + $DatastoreName + ".csv"
$VMList | Export-Csv -Path $FileName1 -NoTypeInformation
}
}