-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertFromBase64Command.cs
More file actions
83 lines (76 loc) · 2.66 KB
/
ConvertFromBase64Command.cs
File metadata and controls
83 lines (76 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Management.Automation;
using System.Text;
namespace PSBinaryModule.Commands
{
/// <summary>
/// Decodes a Base64 string back to its original format.
/// </summary>
[Cmdlet(VerbsData.ConvertFrom, "Base64")]
[OutputType(typeof(Base64ConversionResult))]
public sealed class ConvertFromBase64Command : PSCmdlet
{
/// <summary>
/// Gets or sets the Base64 string to decode.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
HelpMessage = "Base64 string to decode")]
[ValidateNotNullOrEmpty]
public string InputString { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the encoding to use.
/// </summary>
[Parameter(
Mandatory = false,
HelpMessage = "Text encoding to use (UTF8, ASCII, Unicode). Default is UTF8")]
[ValidateSet("UTF8", "ASCII", "Unicode")]
public string Encoding { get; set; } = "UTF8";
protected override void ProcessRecord()
{
try
{
// Get encoding
var enc = GetEncoding(Encoding);
// Decode from Base64
var bytes = Convert.FromBase64String(InputString);
var decoded = enc.GetString(bytes);
// Create result
var inputPreview = InputString.Length > 100
? InputString.AsSpan(0, 100).ToString() + "..."
: InputString;
var result = Base64ConversionResult.FromEncoding(
inputPreview,
decoded,
Encoding);
WriteObject(result);
}
catch (FormatException ex)
{
WriteError(new ErrorRecord(
new FormatException($"The input string is not a valid Base64 string: {ex.Message}", ex),
"InvalidBase64Format",
ErrorCategory.InvalidData,
InputString));
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"DecodingError",
ErrorCategory.InvalidOperation,
InputString));
}
}
private static Encoding GetEncoding(string encodingName)
{
return encodingName switch
{
"ASCII" => System.Text.Encoding.ASCII,
"Unicode" => System.Text.Encoding.Unicode,
_ => System.Text.Encoding.UTF8,
};
}
}
}