I have this script code:
$CurrentDateTime = Get-Date
$CurrentDateTime = $CurrentDateTime.ToString('MM-dd-yyyy_hh-mm-ss')
$servers = @('dc1','dc2','sep1','x5','x6','x7','x8','vum60') # sample list of servers to be inventoried nightly
foreach ($server in $servers) {
get-vm | Select $server, @{ n="DiskUsedGB"; e={[math]::round( $_.UsedSpaceGB, 3 )}}, @{ n="TotalDiskUsedGB"; e={[math]::round( $_.ProvisionedSpaceGB, 3 )}}, @{ n="Date"; e={$CurrentDate}}
}
The foreach part runs over and over again for each server in the list instead of producing just 4 lines per server that I can export to csv.
How do I fix the foreach so it does not do the get-vm over and over again for all servers for each server??
Also how do I correctly add an additional single quote before sep1 so Excel will not read it as a date but as a string??
The result needs to be a list that looks like this that goes into a csv file, instead what I get is the same server name repeated over and over again with different storage numbers
dc1 :
DiskUsedGB : 160.477
TotalDiskUsedGB : 214.180
Date : 10-03-2016_03-57-19
dc2 :
DiskUsedGB : 5.251
TotalDiskUsedGB : 9.161
Date : 10-03-2016_03-57-19
sep1 :
DiskUsedGB : 366.176
TotalDiskUsedGB : 414.210
Date : 10-03-2016_03-57-19
I am doing this with an array b/c not all the VMs must be inventoried.
Thank you, Tom
Hi Tom,
Can you try like below?
$CurrentDateTime = Get-Date
$CurrentDate = $CurrentDateTime.ToString('MM-dd-yyyy_hh-mm-ss')
$servers ='dc1','dc2','sep1','x5','x6','x7','x8','vum60' # sample list of servers to be inventoried nightly
foreach ($server in $servers) {
get-vm $server| Select Name, @{ n="DiskUsedGB"; e={[math]::round( $_.UsedSpaceGB, 3 )}}, @{ n="TotalDiskUsedGB"; e={[math]::round( $_.ProvisionedSpaceGB, 3 )}}, @{ n="Date"; e={$CurrentDate}}
}
The Name parameter accepts a string array. You could do
Get-VM -Name $servers | blah...
I just ran your code against my vCenter, substituting my VM names for yours.
The outputs were what you would expect, i.e. for each VM the 4 properties were displayed. The output wasn't repeated multiple times.
to help with the Sep1 VM being treated as a Date in excel, you could hard type the array to be String only
[string[]]$servers = ...........
What about that?
You can easily add properties as your needs evolve. I find it cleaner this way (That's how I write my scripts anyway).
$CSVFile = 'PathToYourCSVFile'
$CurrentDateTime = (Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')
$servers = @('dc1','dc2','sep1','x5','x6','x7','x8','vum60')
Get-VM $servers | foreach-object {
[pscustomobject]@{
Name =$_.name
DiskUsed =[math]::round($_.UsedSpaceGB,3)
TotalDiskUsedGB =[math]::round($_.ProvisionedSpaceGB,3)
Date =$CurrentDateTime
}
} | Export-CSV $CSVFile