Skip to content

Instantly share code, notes, and snippets.

@dancing-groot
Last active November 29, 2024 20:11
Show Gist options
  • Save dancing-groot/44654c55b767ab8eed6e3edf1a005d30 to your computer and use it in GitHub Desktop.
Save dancing-groot/44654c55b767ab8eed6e3edf1a005d30 to your computer and use it in GitHub Desktop.
Convert-FileToBase64
<#
.SYNOPSIS
Convert a file to a Base64 string
.DESCRIPTION
This is typically used for storing images (PNG/JPG) within a script
Code needs to be updated to cater for BMP and ICO
.LINK
https://gist.github.com/dancing-groot/44654c55b767ab8eed6e3edf1a005d30
.NOTES
Version: 2024.11.29
Author: @dancing-groot
Info: First release
#>
[cmdletBinding()]
param(
[string]$Source
)
#region DECLARATION
# Convert path if the file is in the same folder as the script
if ($Source -like ".\*") { $Source = $Source.Replace(".\", "$PSScriptRoot\") }
# Convert path if the file is in a folder relative to the script's
if ($Source -like "..\*") { $Source = $Source -replace "^\.\.\\", "$PSScriptRoot\..\" }
#endregion DECLARATION
#region MAIN
if (Test-Path -Path $Source -PathType Leaf)
{
$File = Get-ItemProperty -Path $Source
$Folder = $File.DirectoryName
$Filename = $File.Name
if ($Host.Version.Major -le 5)
{
$StringBytes = Get-Content $Source -Encoding Byte
$StringBase64 = [system.convert]::ToBase64String($StringBytes)
}
else
{
$StringBase64 = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($Source))
}
$StringBase64 | Out-File "$Folder\$Filename-BASE64.txt"
}
else
{
Write-Warning "File '$Source' not found"
}
#endregion MAIN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment