Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/System.Management.Automation/utils/EncodingUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,23 @@ internal sealed class ArgumentToEncodingTransformationAttribute : ArgumentTransf
{
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
string encodingName = inputData as String;
Encoding foundEncoding;
if (encodingName != null && EncodingConversion.encodingMap.TryGetValue(encodingName, out foundEncoding))
switch (inputData)
{
return foundEncoding;
case string stringName:
if (EncodingConversion.encodingMap.TryGetValue(stringName, out Encoding foundEncoding))
{
return foundEncoding;
}
else
{
return System.Text.Encoding.GetEncoding(stringName);
}
case int intName:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add some tests for the int case?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added.

return System.Text.Encoding.GetEncoding(intName);
}

return inputData;
}

}

/// <summary>
Expand Down
27 changes: 27 additions & 0 deletions test/powershell/engine/Basic/Encoding.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ Describe "File encoding tests" -Tag CI {
Where-Object { $_.Parameters -and $_.Parameters['Encoding'] } |
ForEach-Object { @{ Command = $_ } }
}

It "Encoding parameter of command '<Command>' is type 'Encoding'" -Testcase $testCases {
param ( $command )
$command.Parameters['Encoding'].ParameterType.FullName | Should -BeExactly "System.Text.Encoding"
}
}

Context "File contents are UTF8 without BOM" {
BeforeAll {
$testStr = "t" + ([char]233) + "st"
Expand Down Expand Up @@ -72,4 +74,29 @@ Describe "File encoding tests" -Tag CI {
$bytes -join "-" | should -Be ($Expected -join "-")
}
}

Context "Parameter 'Encoding' should accept numeric and string Ids" {
BeforeAll {
$testValue = "ф"
if ($IsWindows) {
# Expected bytes: 244 - 'ф', 13 - '`r', 10 - '`n'.
$expectedBytes = 244,13,10 -join "-"
} else {
$expectedBytes = 244,10 -join "-"
}
}

It "Parameter 'Encoding' should accept '<encoding>'" -TestCases @(
@{ encoding = 1251 }
@{ encoding = "windows-1251" }
) {
param ( $encoding )
$testFile = "${TESTDRIVE}/fileEncoding-$($encoding).txt"

Set-Content $testFile -Encoding $encoding -Value $testValue

Get-Content $testFile -Encoding $encoding | Should -BeExactly $testValue
(Get-Content $testFile -AsByteStream) -join "-" | Should -BeExactly $expectedBytes
}
}
}