如何在powershell中使用get-vmhost命令检索时间戳并放入csv文件?

时间:2014-08-23 00:54:31

标签: powershell vcenter

我想将get-vmhost的输出放到带有时间戳的csv文件中。 Get-vmhost命令没有时间戳输出,我试着做timestamp =(get-date),但是当我试图使用管道时,它给了我一个错误。我有什么想法可以在csv文件中插入带有值的时间戳列吗?

if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSsnapin VMware.VimAutomation.Core
}

$Server="dc1-vc.example.com"
Connect-VIServer -server $Server -User <id> -Password <pass>
$Timestamp=(get-date)
Get-VMHost | Where-Object {$_.PowerState -eq "PoweredOn"} | Select-Object Timestamp, Name, NumCpu, CpuUsageMhz, CpuTotalMhz, MemoryUsageGB, MemoryTotalGB |

ConvertTo-Csv  -NoTypeInformation |Out-File -Append -Encoding ascii -FilePath "c:\output\new_dc1.csv"

Disconnect-VIServer -Server $Server -Confirm:$false

错误:

 The term 'Timestamp=' is not recognized as the name of a cmdlet, function, scri
    pt file, or operable program. Check the spelling of the name, or if a path was
    included, verify that the path is correct and try again.

2 个答案:

答案 0 :(得分:2)

$Timestamp=(get-date)
Get-VMHost | Where-Object {$_.PowerState -eq "PoweredOn"} | ForEach-Object{
    "$Timestamp,$($_.Name),$($_.NumCpu),$($_.CpuUsageMhz),$($_.CpuTotalMhz),$($_.MemoryUsageGB),$($_.MemoryTotalGB)" | 
        Out-File -Append -Encoding ascii -FilePath "c:\output\new_dc1.csv"
}

使用您指定的过滤器使用您想要的属性构建一个小的逗号分隔字符串,并添加先前创建的$Timestamp。对于每个Vm,将格式化的代码输出到文件。

如果您有问题,请告诉我,以便我可以更新答案。

答案 1 :(得分:0)

或者你可以使用它:
Get-VMHost | Where-Object {$_.PowerState -eq "PoweredOn"} | Select-Object @{Name="Timestamp";Expression={$Timestamp}}, Name, NumCpu, CpuUsageMhz, CpuTotalMhz, MemoryUsageGB, MemoryTotalGB | ConvertTo-Csv -NoTypeInformation |Out-File -Append -Encoding ascii -FilePath "c:\output\new_dc1.csv"