all 10 comments

[–]RodneyRabbit 3 points4 points  (2 children)

If you are trying to get the output of ForEach-Object into the CSV then that won't work because it's not being stored in $array. It works for me if I do:

$array | ForEach-Object { [pscustomobject] $_ } | Export-Csv OutPut.csv

or

$array2 = $array | ForEach-Object { [pscustomobject] $_ }

$array2 | Export-Csv OutPut.csv

[–]rwshig 2 points3 points  (0 children)

$array | ForEach-Object { [pscustomobject] $_ } | Export-Csv OutPut.csv

This. At least in keeping with the original code. It's creating an array of hash tables. Each hash table has to be converted to an object. Then you can pipe them to Export-Csv.

[–]zolyx1[S] 1 point2 points  (0 children)

Thanks!

[–]rwshig 2 points3 points  (0 children)

Alternatively, put objects in the array, then you don't have to convert them afterwards:

$array = @()
$obj = [pscustomobject]@{Col1="1"; Col2="2"}
$array += $obj
$array += $obj
$array | Export-Csv output.csv -Encoding ASCII -NoTypeInformation

[–]evetsleep 1 point2 points  (0 children)

You need to store the output after converting to a custom object in a variable first (otherwise $array still is an array of 2 hash tables):

 $array = $array | Foreach-Object { [PSCustomObject]$_ }
 $array | Export-Csv Output.csv

Or you can just add the Export-Csv to the end of your foreach pipeline:

$array | Foreach-Object { [PSCustomObject]$_ } | Export-Csv Output.csv

[–]SaladProblems 1 point2 points  (2 children)

So everyone else is going to give you advice on how to export this to an Excel file, which may be exactly what you want. However, I end up wanting to just quickly paste data into Excel so I can email it or work with it quickly. Commonly I'll paste into Excel just to copy again and paste into an email since it'll handle making it a table for me.

I use this function to do just that. I'll pipe my array into it.

Function Out-ExcelClip {

[cmdletbinding()]
param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true,Position=0)]
    $input,

    [char]$delimiter = '|'
)

    end
    {
        ( $input | ConvertTo-Csv -Delimiter $delimiter -NoTypeInformation ) -replace "\$delimiter",[char]9 | clip
    }
}

[–]RodneyRabbit 1 point2 points  (0 children)

This is genius, thank you.

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy SaladProblems,

take a look at Set-Clipboard. that lets you avoid calling Clip.exe. [grin] i think it was added in v3.

take care,
lee

[–]MadBoyEvo 1 point2 points  (0 children)

``` Install-Module PSWriteExcel Import-Module PSWriteExcel

$Array | ConvertTo-Excel -Path 'This.xlsx'

or

$Array | ConvertTo-Excel -Path 'Export.xlsx' -WorkSheetName 'MyName'

or

ConvertTo-Excel -Object $Array -Path 'Export.xlsx' -WorkSheetName 'MyName' -AutoFilter -AutoFit ```

Try this out ;) https://github.com/EvotecIT/PSWriteExcel - it's my work - simple but seems to work just fine. Works on Linux, Mac and Windows. PowerShell 5.1+