Skip to main content

Base64 Encode and Decode PowerShell functions.

function ConvertTo-Base64
{
<#
    .SYNOPSIS
        Function to convert an image to Base64

    .DESCRIPTION
        Function to convert an image to Base64

    .PARAMETER Path
        Specifies the path of the file

    .EXAMPLE
        ConvertTo-Base64 -Path "C:\images\PowerShellLogo.png"

    .NOTES
        Francois-Xavier Cat
        @lazywinadm
        www.lazywinadmin.com
        github.com/lazywinadmin
#>

    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateScript({ Test-Path -Path $_ })]
        [String]$Path
    )
    Write-Verbose -Message "[ConvertTo-Base64] Converting image to Base64 $Path"
    [System.convert]::ToBase64String((Get-Content -Path $path -Encoding Byte))
}

function ConvertFrom-Base64
{
    <#
    .SYNOPSIS
        Converts the specified string, which encodes binary data as base-64
        digits, to an equivalent 8-bit unsigned integer array.

    .DESCRIPTION
        Converts the specified string, which encodes binary data as base-64
        digits, to an equivalent 8-bit unsigned integer array.

    .PARAMETER String
        Specifies the String to Convert

    .EXAMPLE
        ConvertFrom-Base64 -String $ImageBase64 |Out-File ImageTest.png

    .NOTES
        Francois-Xavier Cat
        @lazywinadm
        www.lazywinadmin.com
        github.com/lazywinadmin
#>
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true, ValueFromPipeline)]
        [String]$String
    )

    try
    {
        Write-Verbose -Message "[ConvertFrom-Base64] Converting String"
        [System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String($String))
    }
    catch
    {
        Write-Error -Message "[ConvertFrom-Base64] Something wrong happened"
        $Error[0].Exception.Message
    }
}