Search code examples
powershellvcenter

how do you retrieve timestamp and put into a csv file with get-vmhost command in powershell?


I would like to put the output of get-vmhost to a csv file with a timestamp. Get-vmhost command does not have a timestamp output, I tried to do timestamp=(get-date), but when I tried to use the pipe, it is giving me an error. Any ideas how I could insert a timestamp column in that csv file with values?

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 error:

 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.

Solution

  • $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"
    }
    

    Using the filter you specified build a small comma delimited string using the properties you desire with the addition of the $Timestamp created earlier. For each Vm output the formatted code to the file.

    Let me know if you have issues so i can update the answer.