Skip to content
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.IO;
using System.Management.Automation;
using System.Text;

namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class implements the Get-FileEncoding command.
/// </summary>
[Cmdlet(VerbsCommon.Get, "FileEncoding", DefaultParameterSetName = PathParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=1234567")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We need new link.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah put this one as a placeholder. I will also fill out documentation issue.

[OutputType(typeof(Encoding))]
public sealed class GetFileEncodingCommand : PSCmdlet
{
#region Parameter Sets

private const string PathParameterSet = "ByPath";
private const string LiteralPathParameterSet = "ByLiteralPath";

#endregion

#region Parameters

/// <summary>
/// Gets or sets path from from which to get encoding.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = PathParameterSet)]
public string Path { get; set; }

/// <summary>
/// Gets or sets literal path from which to get encoding.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = LiteralPathParameterSet)]
[Alias("PSPath", "LP")]
public string LiteralPath
{
get
{
return _isLiteralPath ? Path : null;
}

set
{
Path = value;
_isLiteralPath = true;
}
}

private bool _isLiteralPath;

#endregion

/// <summary>
/// Process paths to get file encoding.
/// </summary>
protected override void ProcessRecord()
{
string resolvedPath = PathUtils.ResolveFilePath(Path, this, _isLiteralPath);

if (!File.Exists(resolvedPath))
{
ItemNotFoundException exception = new(Path, "PathNotFound", SessionStateStrings.PathNotFound);
ThrowTerminatingError(exception.ErrorRecord);
}

WriteObject(PathUtils.GetPathEncoding(resolvedPath));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ CmdletsToExport = @(
'Get-TraceSource', 'Set-TraceSource', 'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData',
'Get-UICulture', 'Get-Unique', 'Get-Uptime', 'Clear-Variable', 'Get-Variable', 'New-Variable',
'Remove-Variable', 'Set-Variable', 'Get-Verb', 'Write-Verbose', 'Write-Warning', 'Invoke-WebRequest',
'Format-Wide', 'ConvertTo-Xml', 'Select-Xml', 'Get-Error', 'Update-List', 'Unblock-File'
'Format-Wide', 'ConvertTo-Xml', 'Select-Xml', 'Get-Error', 'Update-List', 'Unblock-File', 'Get-FileEncoding'
)
FunctionsToExport = @()
AliasesToExport = @('fhx')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ CmdletsToExport = @(
'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData', 'Get-UICulture', 'Get-Unique', 'Get-Uptime',
'Clear-Variable', 'Get-Variable', 'New-Variable', 'Remove-Variable', 'Set-Variable', 'Get-Verb', 'Write-Verbose',
'Write-Warning', 'Invoke-WebRequest', 'Format-Wide', 'ConvertTo-Xml', 'Select-Xml', 'Get-Error', 'Update-List',
'Out-GridView', 'Show-Command', 'Out-Printer'
'Out-GridView', 'Show-Command', 'Out-Printer', 'Get-FileEncoding'
)
FunctionsToExport = @()
AliasesToExport = @('fhx')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1241,13 +1241,6 @@ internal TranscriptionOption()
/// </summary>
internal void FlushContentToDisk()
{
static Encoding GetPathEncoding(string path)
{
using StreamReader reader = new StreamReader(path, Encoding.Default, detectEncodingFromByteOrderMarks: true);
_ = reader.Read();
return reader.CurrentEncoding;
}

lock (OutputBeingLogged)
{
if (!_disposed)
Expand All @@ -1256,7 +1249,7 @@ static Encoding GetPathEncoding(string path)
{
try
{
var currentEncoding = GetPathEncoding(this.Path);
var currentEncoding = PathUtils.GetPathEncoding(this.Path);

// Try to first open the file with permissions that will allow us to read from it
// later.
Expand Down
7 changes: 7 additions & 0 deletions src/System.Management.Automation/utils/PathUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,13 @@ private static bool IsDirectorySeparator(char c)
return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar;
}

internal static Encoding GetPathEncoding(string path)
{
using StreamReader reader = new(path, Encoding.Default, detectEncodingFromByteOrderMarks: true);
_ = reader.Read();
return reader.CurrentEncoding;
}

#endregion
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

Describe "Get-FileEncoding" -Tags "CI" {
BeforeAll {
$testFilePath = Join-Path -Path $TestDrive -ChildPath test.txt
$testFileLiteralPath = Join-Path -Path $TestDrive -ChildPath "[test].txt"
$content = 'abc'

$testCases = @(
@{ EncodingName = 'ansi'; ExpectedEncoding = 'utf-8' }
@{ EncodingName = 'ascii'; ExpectedEncoding = 'utf-8' }
@{ EncodingName = 'bigendianunicode'; ExpectedEncoding = 'utf-16BE' }
@{ EncodingName = 'bigendianutf32'; ExpectedEncoding = 'utf-32BE' }
@{ EncodingName = 'oem'; ExpectedEncoding = 'utf-8' }
@{ EncodingName = 'unicode'; ExpectedEncoding = 'utf-16' }
@{ EncodingName = 'utf8'; ExpectedEncoding = 'utf-8' }
@{ EncodingName = 'utf8BOM'; ExpectedEncoding = 'utf-8' }
@{ EncodingName = 'utf8NoBOM'; ExpectedEncoding = 'utf-8' }
@{ EncodingName = 'utf32'; ExpectedEncoding = 'utf-32' }
)
}

It "Validate Get-FileEncoding using -Path returns file encoding for '<EncodingName>'" -TestCases $testCases {
param($EncodingName, $ExpectedEncoding)
Set-Content -Path $testFilePath -Encoding $EncodingName -Value $content -Force
(Get-FileEncoding -Path $testFilePath).BodyName | Should -Be $ExpectedEncoding
(Get-ChildItem -Path $testFilePath | Get-FileEncoding).BodyName | Should -Be $ExpectedEncoding
}

It "Validate Get-FileEncoding using -LiteralPath returns file encoding for '<EncodingName>'" -TestCases $testCases {
param($EncodingName, $ExpectedEncoding)
Set-Content -LiteralPath $testFileLiteralPath -Encoding $EncodingName -Value $content -Force
(Get-FileEncoding -LiteralPath $testFileLiteralPath).BodyName | Should -Be $ExpectedEncoding
(Get-ChildItem -LiteralPath $testFileLiteralPath | Get-FileEncoding).BodyName | Should -Be $ExpectedEncoding
}

It "Should throw exception if path is not found using -Path" {
{ Get-FileEncoding -Path nonexistentpath } | Should -Throw -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetFileEncodingCommand'
}

It "Should throw exception if path is not found using -LiteralPath" {
{ Get-FileEncoding -LiteralPath nonexistentpath } | Should -Throw -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetFileEncodingCommand'
}
}
1 change: 1 addition & 0 deletions test/powershell/engine/Basic/DefaultCommands.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ Describe "Verify aliases and cmdlets" -Tags "CI" {
"Cmdlet", "Get-EventSubscriber", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "Get-ExecutionPolicy", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "Get-ExperimentalFeature", "", $( $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "Get-FileEncoding", "", $( $CoreWindows -or $CoreUnix), "", "", "None",
"Cmdlet", "Get-FileHash", "", $( $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "Get-FormatData", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "Get-Help", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
Expand Down