ConvertTo-Csv: Quote fields with quotes and newlines when using -UseQuotes AsNeeded (#15765)

Co-authored-by: Ilya <darpa@yandex.ru>
Co-authored-by: lselden <luke.selden@vbrick.com>
This commit is contained in:
lselden 2021-08-04 17:47:57 -04:00 committed by GitHub
parent 5fea4c39fd
commit 3e86f9b287
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 2 deletions

View file

@ -992,7 +992,8 @@ namespace Microsoft.PowerShell.Commands
AppendStringWithEscapeAlways(_outputString, propertyName);
break;
case BaseCsvWritingCommand.QuoteKind.AsNeeded:
if (propertyName.Contains(_delimiter))
if (propertyName.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1)
{
AppendStringWithEscapeAlways(_outputString, propertyName);
}
@ -1078,7 +1079,7 @@ namespace Microsoft.PowerShell.Commands
AppendStringWithEscapeAlways(_outputString, value);
break;
case BaseCsvWritingCommand.QuoteKind.AsNeeded:
if (value != null && value.Contains(_delimiter))
if (value != null && value.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1)
{
AppendStringWithEscapeAlways(_outputString, value);
}

View file

@ -159,6 +159,45 @@ Describe "ConvertTo-Csv" -Tags "CI" {
$result[0] | Should -BeExactly "`"FirstColumn`"rSecondColumn"
$result[1] | Should -BeExactly "Hellor"
}
It "UseQuotes AsNeeded Escapes Delimiters" {
$testDelimitersObject = [pscustomobject]@{ "FirstColumn" = "Hello,"; "Second,Column" = "World" };
$result = $testDelimitersObject | ConvertTo-Csv -UseQuotes AsNeeded -Delimiter ','
$result[0] | Should -BeExactly "FirstColumn,`"Second,Column`""
$result[1] | Should -BeExactly "`"Hello,`",World"
$result = $testDelimitersObject | ConvertTo-Csv -UseQuotes AsNeeded -Delimiter "r"
$result[0] | Should -BeExactly "`"FirstColumn`"rSecond,Column"
$result[1] | Should -BeExactly "Hello,r`"World`""
}
It "UseQuotes AsNeeded Escapes Newlines" {
$testCRLFObject = [pscustomobject]@{ "First`r`nColumn" = "Hello`r`nWorld" };
$testLFObject = [pscustomobject]@{ "First`nColumn" = "Hello`nWorld" };
$result = $testCRLFObject | ConvertTo-Csv -UseQuotes AsNeeded
$result[0] | Should -BeExactly "`"First`r`nColumn`""
$result[1] | Should -BeExactly "`"Hello`r`nWorld`""
$result = $testLFObject | ConvertTo-Csv -UseQuotes AsNeeded
$result[0] | Should -BeExactly "`"First`nColumn`""
$result[1] | Should -BeExactly "`"Hello`nWorld`""
}
It "UseQuotes AsNeeded Escapes Quotes" {
$testQuotesObject = [pscustomobject]@{ "First`"Column" = "`"Hello`" World" };
$result = $testQuotesObject | ConvertTo-Csv -UseQuotes AsNeeded
$result[0] | Should -BeExactly "`"First`"`"Column`""
$result[1] | Should -BeExactly "`"`"`"Hello`"`" World`""
}
}
Context 'Converting IDictionary Objects' {