Skip to content

ConvertTo-Csv and Export-Csv fail when -usequotes asneeded option is used and input object has null properties #12279

@zmajeed

Description

@zmajeed

This happened when I tried to export Windows event logs that had events with no messages.

I've included a small test case

Steps to reproduce

# Unexpected error with `-usequotes asneeded`
PS> $a=@(
           [pscustomobject]@{a=2; b=5},
           [pscustomobject]@{a=4; b=$null}
       )
PS> $a | convertto-csv -d `t -usequotes asneeded
a       b
2       5

ConvertTo-Csv: Object reference not set to an instance of an object.

Expected behavior

Expect output to match -usequotes never in this case

PS> $a | convertto-csv -d `t -usequotes never
a       b
2       5
4

PS> $a | convertto-csv -d `t -usequotes always
"a"     "b"
"2"     "5"
"4"

Actual behavior

Here's the same error with export-csv when exporting an event log with an empty message

# this does not work
PS> get-winevent -logname application |
        ? {$_.message -eq $null} |
        select -first 1 timecreated,providername,message |
        export-csv -d `t -usequotes asneeded -path out.txt

TimeCreated     ProviderName    Message

Export-Csv: Object reference not set to an instance of an object.

Here's the actual event log entry

# this works
PS> get-winevent -logname application |
        ? {$_.message -eq $null} |
        select -first 1 timecreated,providername,message |
        fl *

TimeCreated  : 4/7/2020 6:32:19 PM
ProviderName : gupdate
Message      :

# this works
PS> get-winevent -logname application |
        ? {$_.message -eq $null} |
        select -first 1 timecreated,providername,message |
        convertto-csv -d `t

"TimeCreated"   "ProviderName"  "Message"
"4/7/2020 6:32:19 PM"   "gupdate"

Environment data

Name                           Value
----                           -----
PSVersion                      7.0.0
PSEdition                      Core
GitCommitId                    7.0.0
OS                             Microsoft Windows 10.0.18362
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugIssue has been identified as a bug in the productWG-Cmdlets-Utilitycmdlets in the Microsoft.PowerShell.Utility module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions