Reputation: 23
I'm trying to get Information about our VMs in Hyper-V via PowerShell.
This is what I got so far:
$Path = 'c:/VM.csv'
"Name,CPUs,Dynamischer Arbeitsspeicher,RAM Maximum (in MB),RAM Minimum (in MB), Size" > $Path
$line1 = Get-VM | %{($_.Name, $_.ProcessorCount, $_.DynamicMemoryEnabled, ($_.MemoryMaximum/1MB), ($_.MemoryMinimum/1MB)) -join ","}
$line2 = Get-VM –VMName * | Select-Object VMId | Get-VHD | %{$_.FileSize/1GB -join ","}
$out = $line1+","+ $line2
Write-Output $out | Out-File $Path -Append
Import-Csv -Path $Path | Out-GridView
The Problem is that the second object ($line2
) should be in the same column as $line1
. As you can see, currently the information about the size of the VMs ($line2
) is written in rows under the output of $line1
. Also the order is wrong.
Any idea what is wrong with my code?
Thanks in advance.
Upvotes: 1
Views: 125
Reputation: 8899
I think you messed it up a little,
Export-CSV
will do the job without the need to manually define the csv structure.
Anyway, regarding your code I think you can improve it a little, (I don't have hyper-v to test this, but I think it should work)
What I've done is create a results array to hold the final data, then using foreach loop i'm iterating the Get-VM
Results and creating a row for each VM, at the end of each iteration I'm adding the row to the final results array, so:
$Results = @()
foreach ($VM in (Get-VM))
{
$Row = "" | Select Name,CPUs,'Dynamischer Arbeitsspeicher','RAM Maximum (inMB)','RAM Minimum (in MB)',Size
$Row.Name = $VM.Name
$Row.CPUs = $VM.ProcessorCount
$Row.'Dynamischer Arbeitsspeicher' = $VM.DynamicMemoryEnabled
$Row.'RAM Maximum (inMB)' = $VM.MemoryMaximum/1MB
$Row.'RAM Minimum (in MB)' = $VM.MemoryMinimum/1MB
$Total=0; ($VM.VMId | Get-VHD | %{$Total += ($_.FileSize/1GB)})
$Row.Size = [math]::Round($Total)
$Results += $Row
}
$Results | Export-Csv c:\vm.csv -NoTypeInformation
Upvotes: 1
Reputation: 23862
This is definitely not the proper way to build an object list, instead you should do something like this:
Get-VM | Select Name,
@{Name = "CPUs"; Expression = {$_.ProcessorCount},
@{Name = "Dynamischer Arbeitsspeicher"; Expression = {$_.DynamicMemoryEnabled},
@{Name = "RAM Maximum (in MB)"; Expression = {$_.MemoryMaximum/1MB},
@{Name = "RAM Minimum (in MB)"; Expression = {$_.MemoryMinimum/1MB},
@{Name = "Size"; Expression = {$_.VMId | Get-VHD | %{$_.FileSize/1GB -join ","}} |
Export-Csv c:\vm.csv -NoTypeInformation
Upvotes: 0