diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index cb6e4a9024d..397ca036151 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -1013,7 +1013,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN AppendStringWithEscapeAlways(_outputString, value); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (value.Contains(_delimiter)) + if (value != null && value.Contains(_delimiter)) { AppendStringWithEscapeAlways(_outputString, value); } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 index 7d91b0b4bfd..494051507f7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 @@ -40,6 +40,7 @@ Describe "ConvertTo-Csv" -Tags "CI" { BeforeAll { $Name = "Hello"; $Data = "World"; $testObject = [pscustomobject]@{ FirstColumn = $Name; SecondColumn = $Data } + $testNullObject = [pscustomobject]@{ FirstColumn = $Name; SecondColumn = $null } } It "Should Be able to be called without error" { @@ -121,6 +122,11 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result[0] | Should -BeExactly "`"FirstColumn`",`"SecondColumn`"" $result[1] | Should -BeExactly "`"Hello`",`"World`"" + + $result = $testNullObject | ConvertTo-Csv -UseQuotes Always -Delimiter ',' + + $result[0] | Should -BeExactly "`"FirstColumn`",`"SecondColumn`"" + $result[1] | Should -BeExactly "`"Hello`"," } It "UseQuotes Always is default" { @@ -135,6 +141,11 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result[0] | Should -BeExactly "FirstColumn,SecondColumn" $result[1] | Should -BeExactly "Hello,World" + + $result = $testNullObject | ConvertTo-Csv -UseQuotes Never -Delimiter ',' + + $result[0] | Should -BeExactly "FirstColumn,SecondColumn" + $result[1] | Should -BeExactly "Hello," } It "UseQuotes AsNeeded" { @@ -142,6 +153,11 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result[0] | Should -BeExactly "`"FirstColumn`"rSecondColumn" $result[1] | Should -BeExactly "Hellor`"World`"" + + $result = $testNullObject | ConvertTo-Csv -UseQuotes AsNeeded -Delimiter 'r' + + $result[0] | Should -BeExactly "`"FirstColumn`"rSecondColumn" + $result[1] | Should -BeExactly "Hellor" } } }