如何在PowerShell中连接两行

时间:2017-11-27 09:39:31

标签: powershell csv

我试图通过PowerShell在Hyper-V中获取有关我们虚拟机的信息。

这是我到目前为止所得到的:

$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

问题是第二个对象($line2)应与$line1在同一列中。如您所见,目前有关VM大小的信息($line2)在$line1的输出下按行写入。订单也是错误的。

知道我的代码有什么问题吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

我觉得你搞砸了一下,

Export-CSV无需手动定义csv结构即可完成工作。

无论如何,关于你的代码,我认为你可以稍微改进一下,(我没有超级v来测试这个,但我认为它应该有效)

我所做的是创建一个结果数组来保存最终数据,然后使用foreach循环我迭代Get-VM结果并为每个VM创建一行,最后每次迭代我都将行添加到最终结果数组中,所以:

$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

答案 1 :(得分:0)

这绝对不是构建对象列表的正确方法,而是应该这样做:

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