Danijel de Vasco
Danijel de Vasco

Reputation: 53

powershell: Write specific rows from files to formatted csv

The following code gives me the correct output to console. But I would need it in a csv file:

$array = @{}
$files = Get-ChildItem "C:\Temp\Logs\*"
foreach($file in $files){
    foreach($row in (Get-Content $file | select -Last 2)){
        if($row -like "Total peak job memory used:*"){
            $sp_memory = $row.Split(" ")[5]
            $array.Add(($file.BaseName),([double]$sp_memory))
            break
        }
    } 
}
$array.GetEnumerator() | sort Value -Descending |Format-Table -AutoSize

current output (console):

Output console:

required output (csv):

enter image description here

In order to increase performance I would like to avoid the array and write output directly to csv (no append).

Thanks in advance!

Upvotes: 0

Views: 1013

Answers (1)

Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

Change your last line to this -

$array.GetEnumerator() | sort Value -Descending | select @{l='FileName'; e={$_.Name}}, @{l='Memory (MB)'; e={$_.Value }} | Export-Csv -path $env:USERPROFILE\Desktop\Output.csv -NoTypeInformation

This will give you a csv file named Output.csv on your desktop. I am using Calculated properties to change the column headers to FileName and Memory (MB) and piping the output of $array to Export-Csv cmdlet.

Just to let you know, your variable $array is of type Hashtable which won't store duplicate keys. If you need to store duplicate key/value pairs, you can use arrays. Just suggesting! :)

Upvotes: 1

Related Questions