-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertTo-Base64.ps1
More file actions
197 lines (160 loc) · 5.88 KB
/
Copy pathConvertTo-Base64.ps1
File metadata and controls
197 lines (160 loc) · 5.88 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
function ConvertTo-Base64
{
<#
.SYNOPSIS
Converts a string or file content to Base64 encoding.
.DESCRIPTION
Encodes input text or file content to Base64 format. Supports both standard
and URL-safe Base64 encoding. Can accept input from pipeline, parameters,
or read from files.
Cross-platform compatible with PowerShell 5.1+ and PowerShell Core.
Aliases:
The 'encode-base64' alias is created only if it doesn't already exist in the current environment.
.PARAMETER InputObject
The string to encode. Can be provided via pipeline.
.PARAMETER Path
Path to a file whose content should be encoded.
.PARAMETER UrlSafe
Use URL-safe Base64 encoding (replaces + with -, / with _, and removes padding =).
.EXAMPLE
PS > ConvertTo-Base64 -InputObject 'Hello World'
SGVsbG8gV29ybGQ=
Encodes a simple string to Base64.
.EXAMPLE
PS > 'Hello World' | ConvertTo-Base64
SGVsbG8gV29ybGQ=
Encodes a string from pipeline input.
.EXAMPLE
PS > ConvertTo-Base64 -InputObject 'Hello World' -UrlSafe
SGVsbG8gV29ybGQ
Encodes a string using URL-safe Base64 (no padding).
.EXAMPLE
PS > ConvertTo-Base64 -Path './document.txt'
VGhpcyBpcyBhIHRlc3QgZmlsZQ==
Encodes the content of a file to Base64.
.EXAMPLE
PS > $base64 = ConvertTo-Base64 -Path './logo.png'
PS > $imgSrc = "data:image/png;base64,$base64"
PS > "<img src='$imgSrc' alt='Logo' />"
Creates a data URI for a PNG so it can be embedded directly in an HTML img tag.
.EXAMPLE
PS > Get-Content './data.txt' | ConvertTo-Base64
VGVzdCBkYXRh
Encodes text from stdin/pipeline.
.EXAMPLE
PS > $svg = '<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><circle cx="20" cy="20" r="18" fill="red"/></svg>'
PS > $base64 = ConvertTo-Base64 -InputObject $svg
PS > $svgSrc = "data:image/svg+xml;base64,$base64"
PS > "<img src='$svgSrc' alt='Badge' />"
Encodes inline SVG markup for embedding as an HTML image source.
.EXAMPLE
PS > $token = ConvertTo-Base64 -InputObject 'client-id:client-secret'
PS > Invoke-RestMethod -Uri $api -Headers @{ Authorization = "Basic $token" }
Generates an HTTP Basic authorization header without relying on external tooling.
.EXAMPLE
PS > $payload = Get-Content './config.json' -Raw | ConvertTo-Base64
PS > Invoke-RestMethod -Method Post -Uri $api -Body @{ config = $payload }
Packs a JSON configuration file into Base64 so it can be shipped in an API request body.
.OUTPUTS
System.String
The Base64-encoded string.
.NOTES
For URL-safe encoding, the output follows RFC 4648 Section 5.
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/ConvertTo-Base64.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/ConvertTo-Base64.ps1
#>
[CmdletBinding(DefaultParameterSetName = 'String')]
[OutputType([String])]
param(
[Parameter(
Mandatory,
ValueFromPipeline,
ParameterSetName = 'String',
Position = 0
)]
[AllowEmptyString()]
[String]$InputObject,
[Parameter(
Mandatory,
ParameterSetName = 'File'
)]
[ValidateScript({
if (-not (Test-Path -Path $_ -PathType Leaf))
{
throw "File not found: $_"
}
$true
})]
[String]$Path,
[Parameter()]
[Switch]$UrlSafe
)
begin
{
Write-Verbose 'Starting Base64 encoding'
$results = [System.Collections.ArrayList]::new()
}
process
{
try
{
if ($PSCmdlet.ParameterSetName -eq 'File')
{
# Resolve path to absolute path
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
Write-Verbose "Reading file: $resolvedPath"
# Read file as bytes
$bytes = [System.IO.File]::ReadAllBytes($resolvedPath)
$base64 = [System.Convert]::ToBase64String($bytes)
}
else
{
# Encode string input
$bytes = [System.Text.Encoding]::UTF8.GetBytes($InputObject)
$base64 = [System.Convert]::ToBase64String($bytes)
}
# Apply URL-safe encoding if requested
if ($UrlSafe)
{
$base64 = $base64.Replace('+', '-').Replace('/', '_').TrimEnd('=')
Write-Verbose 'Applied URL-safe encoding'
}
# Accumulate results for pipeline input
$null = $results.Add($base64)
}
catch
{
Write-Error "Failed to encode to Base64: $($_.Exception.Message)"
throw
}
}
end
{
# 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 encoding completed'
}
}
# Create 'encode-base64' alias only if it doesn't already exist
if (-not (Get-Command -Name 'encode-base64' -ErrorAction SilentlyContinue))
{
try
{
Write-Verbose "Creating 'encode-base64' alias for ConvertTo-Base64"
Set-Alias -Name 'encode-base64' -Value 'ConvertTo-Base64' -Force -ErrorAction Stop
}
catch
{
Write-Warning "ConvertTo-Base64: Could not create 'encode-base64' alias: $($_.Exception.Message)"
}
}