简体   繁体   中英

Formatting the output data in csv from powershell script

I'm trying to fetch the perfmon counters and exporting the data to csv file.

$pg_co = "\Processor(_total)\% processor time"
$pg_Da = Get-Counter $pg_co

$pg_Da.counterSamples | Select-Object TimeStamp, CookedValue, RawValue | Export-CSV "D:\Qemu\test1.csv" -Append -NoTypeInformation

$pg_co = "\Memory\Available MBytes"
$pg_Da = Get-Counter $pg_co

$pg_Da.counterSamples | Select-Object TimeStamp, CookedValue, RawValue | Export-CSV "D:\Qemu\test1.csv" -Append -NoTypeInformation

But I'm unable to put these values in individual columns. The data gets overwritten(or in subsequent rows if I include -Append). When I query the counter for the second time, how can I put it in a new column? For example, I would want the csv to look like this, maybe with a different column name as CookedValue2 or anything. The expect outlook of csv file Any help would be greatly appreciated

Try this:

$pg_co1 ="\Processor(_total)\% processor time"
$pg_Da1 = Get-Counter $pg_co1

$pg_co2 ="\Memory\Available MBytes"
$pg_Da2 = Get-Counter $pg_co

$csv = New-Object -TypeName PSObject 

Add-Member -InputObject $csv -MemberType NoteProperty -Name "TimeStamp" -Value $pg_Da1.Timestamp
Add-Member -InputObject $csv -MemberType NoteProperty -Name "CookiedValue1" -Value $pg_Da1.CounterSamples[0].CookedValue
Add-Member -InputObject $csv -MemberType NoteProperty -Name "CookiedValue2" -Value $pg_Da2.CounterSamples[0].CookedValue
Add-Member -InputObject $csv -MemberType NoteProperty -Name "RawValue1" -Value $pg_Da1.CounterSamples[0].RawValue
Add-Member -InputObject $csv -MemberType NoteProperty -Name "RawValue2" -Value $pg_Da2.CounterSamples[0].RawValue

$csv | Export-Csv "D:\Qemu\test1.csv" -NoTypeInformation -Append

it make this kind of csv:

"TimeStamp","CookiedValue1","CookiedValue2","RawValue1","RawValue2"
"27.03.2017 16:33:21","3,91259176894325","0,782341394244668","450438906250","450448828125"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM