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:
parent
5fea4c39fd
commit
3e86f9b287
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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' {
|
||||
|
|
Loading…
Reference in a new issue