rawrPowershell
rawrPowershell

Reputation: 124

Powershell Append CSV fail

I am fairly new to powershell, but when I try to run this portion of the code, it works sometimes, but I usually get an error message:

"Method invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'."

It seems to fail when I add $in + $o, and it has worked in the past. I haven't changed anything for it to stop working though. I am trying to append to a csv, and I have tried Export-CSV -append, however that does not work for me. Any ideas on what might be wrong with this code?

    $in = Import-Csv $csv

    $obj = New-Object PSObject
    $obj | Add-Member NoteProperty Column1 "$c1"
    $obj | Add-Member NoteProperty Column2 "$c2"
    $obj | Add-Member NoteProperty Column3 "$c3"

    $in + $obj | Export-Csv -Encoding ASCII -NoTypeInformation $csv

Upvotes: 1

Views: 1528

Answers (1)

Keith Hill
Keith Hill

Reputation: 201592

That probably worked before when $in is an array. However if you read in a CSV with just a single element it will fail. You can do this instead in PowerShell 3.0 (you don't need to even read in $in):

$obj | Export-Csv $csv -Encoding ASCII -NoTypeInformation -Append

The -Append parameter on Export-Csv is new in PowerShell 3.0. If you don't have 3.0 then modify this line:

$in = @(Import-Csv $csv)

Then it should work. That makes sure that $in is always an array.

Upvotes: 3

Related Questions