-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertFrom-Base64.ps1
More file actions
204 lines (168 loc) · 6.34 KB
/
Copy pathConvertFrom-Base64.ps1
File metadata and controls
204 lines (168 loc) · 6.34 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
function ConvertFrom-Base64
{
<#
.SYNOPSIS
Decodes a Base64-encoded string to its original text or file content.
.DESCRIPTION
Decodes Base64-encoded input back to plain text or writes binary content to a file.
Supports both standard and URL-safe Base64 decoding. Can accept input from pipeline
or parameters.
Cross-platform compatible with PowerShell 5.1+ and PowerShell Core.
Aliases:
The 'decode-base64' alias is created only if it doesn't already exist in the current environment.
.PARAMETER InputObject
The Base64-encoded string to decode. Can be provided via pipeline.
.PARAMETER OutputPath
Optional path to write decoded binary content to a file. If not specified,
the decoded content is returned as a UTF-8 string.
.PARAMETER UrlSafe
Indicates that the input uses URL-safe Base64 encoding (- instead of +, _ instead of /).
.EXAMPLE
PS > ConvertFrom-Base64 -InputObject 'SGVsbG8gV29ybGQ='
Hello World
Decodes a Base64 string to plain text.
.EXAMPLE
PS > 'SGVsbG8gV29ybGQ=' | ConvertFrom-Base64
Hello World
Decodes a Base64 string from pipeline input.
.EXAMPLE
PS > ConvertFrom-Base64 -InputObject 'SGVsbG8gV29ybGQ' -UrlSafe
Hello World
Decodes a URL-safe Base64 string (no padding).
.EXAMPLE
PS > ConvertFrom-Base64 -InputObject 'VGhpcyBpcyBhIHRlc3QgZmlsZQ==' -OutputPath './decoded.txt'
Decodes Base64 content and writes it to a file.
.EXAMPLE
PS > Get-Content './encoded.txt' | ConvertFrom-Base64
Decoded content here
Decodes Base64 text from stdin/pipeline.
.EXAMPLE
PS > $token = ConvertTo-Base64 -InputObject 'client-id:client-secret'
PS > ConvertFrom-Base64 -InputObject $token
client-id:client-secret
Quickly inspects what was placed inside an HTTP Basic authorization header.
.EXAMPLE
PS > $dataUri = Get-Content './image.txt'
PS > $base64 = $dataUri -replace '^data:image/[^;]+;base64,', ''
PS > ConvertFrom-Base64 -InputObject $base64 -OutputPath './restored.png'
Strips the prefix from a data URI and writes the decoded image back to disk.
.OUTPUTS
System.String
The decoded text (when OutputPath is not specified).
.NOTES
For URL-safe decoding, the input follows RFC 4648 Section 5.
When writing to a file, the function handles binary data correctly.
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/ConvertFrom-Base64.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/ConvertFrom-Base64.ps1
#>
[CmdletBinding(DefaultParameterSetName = 'ToString')]
[OutputType([String])]
param(
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[ValidateNotNullOrEmpty()]
[String]$InputObject,
[Parameter(
ParameterSetName = 'ToFile'
)]
[String]$OutputPath,
[Parameter()]
[Switch]$UrlSafe
)
begin
{
Write-Verbose 'Starting Base64 decoding'
$results = [System.Collections.ArrayList]::new()
}
process
{
try
{
# Prepare the Base64 string
$base64String = $InputObject
# Convert from URL-safe encoding if requested
if ($UrlSafe)
{
$base64String = $base64String.Replace('-', '+').Replace('_', '/')
# Add padding if needed
$remainder = $base64String.Length % 4
if ($remainder -gt 0)
{
$base64String += '=' * (4 - $remainder)
}
Write-Verbose 'Converted from URL-safe encoding'
}
# Decode from Base64
$bytes = [System.Convert]::FromBase64String($base64String)
if ($PSCmdlet.ParameterSetName -eq 'ToFile')
{
# Write binary content to file
if (-not $OutputPath)
{
throw 'OutputPath parameter is required for file output'
}
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath)
Write-Verbose "Writing decoded content to: $resolvedPath"
# Ensure directory exists
$directory = [System.IO.Path]::GetDirectoryName($resolvedPath)
if ($directory -and -not (Test-Path -Path $directory))
{
$null = New-Item -Path $directory -ItemType Directory -Force
}
[System.IO.File]::WriteAllBytes($resolvedPath, $bytes)
Write-Verbose "Successfully wrote $($bytes.Length) bytes to file"
}
else
{
# Convert bytes to UTF-8 string
$decodedText = [System.Text.Encoding]::UTF8.GetString($bytes)
$null = $results.Add($decodedText)
}
}
catch [System.FormatException]
{
Write-Error "Invalid Base64 string: $($_.Exception.Message)"
throw
}
catch
{
Write-Error "Failed to decode from Base64: $($_.Exception.Message)"
throw
}
}
end
{
if ($PSCmdlet.ParameterSetName -eq 'ToString')
{
# For single result, return as-is; for multiple, join with newlines
if ($results.Count -eq 1)
{
Write-Output $results[0]
}
elseif ($results.Count -gt 1)
{
Write-Output ($results -join [Environment]::NewLine)
}
}
Write-Verbose 'Base64 decoding completed'
}
}
# Create 'decode-base64' alias only if it doesn't already exist
if (-not (Get-Command -Name 'decode-base64' -ErrorAction SilentlyContinue))
{
try
{
Write-Verbose "Creating 'decode-base64' alias for ConvertFrom-Base64"
Set-Alias -Name 'decode-base64' -Value 'ConvertFrom-Base64' -Force -ErrorAction Stop
}
catch
{
Write-Warning "ConvertFrom-Base64: Could not create 'decode-base64' alias: $($_.Exception.Message)"
}
}