Yo! Base64 Decode logoYo! Base64 Decode
PowerShell

How to Base64 Decode Data in PowerShell

Learn how to efficiently decode Base64 data using PowerShell with practical examples and script solutions. Master file handling, automation, and string manipulation techniques.

By Ishan Karunaratne3 min read

Base64 decoding is a common task when working with encoded data in PowerShell scripts. Whether you're processing email attachments, handling API responses, or working with encoded files, PowerShell provides robust tools for Base64 decoding. Let's explore how to implement this effectively.

Looking to encode strings instead? Check out our guide on How to Base64 Encode Data in PowerShell.

Basic Base64 Decoding

PowerShell makes it straightforward to decode Base64 strings using built-in cmdlets:

POWERSHELL
# Simple string decoding
$encodedString = "SGVsbG8sIFdvcmxkIQ=="
$decodedText = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encodedString))
Write-Output $decodedText  # Output: Hello, World!

Working with Files

Here's how to decode Base64-encoded files:

POWERSHELL
# Decode a file
function Convert-FromBase64File {
    param(
        [Parameter(Mandatory=$true)]
        [string]$InputFile,
        
        [Parameter(Mandatory=$true)]
        [string]$OutputFile
    )
    
    try {
        $content = Get-Content $InputFile -Raw
        $bytes = [System.Convert]::FromBase64String($content)
        [System.IO.File]::WriteAllBytes($OutputFile, $bytes)
        Write-Output "File decoded successfully to: $OutputFile"
    }
    catch {
        Write-Error "Error decoding file: $_"
    }
}

Advanced Decoding Techniques

Creating a Robust Decoder Function

Let's build a versatile decoder that handles various input types:

POWERSHELL
function ConvertFrom-Base64 {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]$InputData,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet('UTF8', 'ASCII', 'Unicode')]
        [string]$Encoding = 'UTF8'
    )
    
    process {
        try {
            # Remove whitespace and validate
            $cleanInput = $InputData.Trim()
            if ([string]::IsNullOrEmpty($cleanInput)) {
                throw "Input string is empty"
            }
            
            # Add padding if necessary
            while ($cleanInput.Length % 4) {
                $cleanInput += "="
            }
            
            # Decode the string
            $bytes = [System.Convert]::FromBase64String($cleanInput)
            $decodedText = [System.Text.Encoding]::$Encoding.GetString($bytes)
            
            return $decodedText
        }
        catch {
            Write-Error "Failed to decode Base64 string: $_"
        }
    }
}

Handling Binary Data

When working with binary files:

POWERSHELL
function Convert-Base64ToBinary {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Base64String,
        
        [Parameter(Mandatory=$true)]
        [string]$OutputPath
    )
    
    try {
        $bytes = [System.Convert]::FromBase64String($Base64String)
        [System.IO.File]::WriteAllBytes($OutputPath, $bytes)
        Write-Output "Binary file created successfully at: $OutputPath"
    }
    catch {
        Write-Error "Error creating binary file: $_"
        return $false
    }
}

Practical Applications

Processing Multiple Files

Create a script to handle multiple encoded files:

POWERSHELL
function Process-Base64Files {
    param(
        [Parameter(Mandatory=$true)]
        [string]$InputFolder,
        
        [Parameter(Mandatory=$true)]
        [string]$OutputFolder
    )
    
    # Create output folder if it doesn't exist
    if (!(Test-Path $OutputFolder)) {
        New-Item -ItemType Directory -Path $OutputFolder
    }
    
    # Process each .b64 file
    Get-ChildItem $InputFolder -Filter "*.b64" | ForEach-Object {
        $outputFile = Join-Path $OutputFolder ($_.BaseName + ".decoded")
        
        try {
            $content = Get-Content $_.FullName -Raw
            $bytes = [System.Convert]::FromBase64String($content)
            [System.IO.File]::WriteAllBytes($outputFile, $bytes)
            Write-Output "Successfully decoded: $($_.Name)"
        }
        catch {
            Write-Error "Error processing $($_.Name): $_"
        }
    }
}

Decoding Email Attachments

Handle Base64-encoded email attachments:

POWERSHELL
function Decode-EmailAttachment {
    param(
        [Parameter(Mandatory=$true)]
        [string]$EncodedContent,
        
        [Parameter(Mandatory=$true)]
        [string]$OutputPath
    )
    
    # Remove email headers and footers
    $cleanContent = $EncodedContent -replace "`r`n", "" `
                                   -replace "^[^a-zA-Z0-9+/=]*", "" `
                                   -replace "[^a-zA-Z0-9+/=]*$", ""
    
    try {
        $bytes = [System.Convert]::FromBase64String($cleanContent)
        [System.IO.File]::WriteAllBytes($OutputPath, $bytes)
        return $true
    }
    catch {
        Write-Error "Failed to decode attachment: $_"
        return $false
    }
}

Error Handling and Validation

Input Validation Function

POWERSHELL
function Test-Base64String {
    param(
        [Parameter(Mandatory=$true)]
        [string]$InputString
    )
    
    try {
        # Check for valid Base64 characters
        if ($InputString -match '[^a-zA-Z0-9+/=]') {
            return $false
        }
        
        # Try to decode
        [System.Convert]::FromBase64String($InputString) | Out-Null
        return $true
    }
    catch {
        return $false
    }
}

Secure Decoding Implementation

POWERSHELL
function Secure-Base64Decode {
    param(
        [Parameter(Mandatory=$true)]
        [string]$InputData,
        
        [Parameter(Mandatory=$false)]
        [switch]$ValidateOnly
    )
    
    # Validate input
    if (!(Test-Base64String $InputData)) {
        Write-Error "Invalid Base64 string provided"
        return $null
    }
    
    if ($ValidateOnly) {
        return $true
    }
    
    try {
        $bytes = [System.Convert]::FromBase64String($InputData)
        return [System.Text.Encoding]::UTF8.GetString($bytes)
    }
    catch {
        Write-Error "Decoding error: $_"
        return $null
    }
}

Conclusion

Base64 decoding in PowerShell offers flexible and powerful options for handling encoded data. Whether you're working with simple strings or processing multiple files, these tools and techniques provide robust solutions for your decoding needs. Remember to implement proper error handling and validation for reliable script execution.

Frequently Asked Questions

Q1: How do I handle Base64 strings with line breaks? A: Use -replace "\s+" to remove all whitespace before decoding: $cleanString = $encodedString -replace "\s+", ""

Q2: What's the maximum size of Base64 string PowerShell can handle? A: PowerShell can handle large strings, but for better performance with large files, process them in chunks using streams.

Q3: How can I verify if a string is valid Base64? A: Use the Test-Base64String function provided above, which checks for valid characters and attempts a test decode.

Q4: Can PowerShell decode Base64URL format? A: Yes, but you need to replace URL-safe characters first: $standard = $urlSafe -replace '-', '+' -replace '_', '/'

Q5: How do I handle encoding issues when decoding Base64? A: Specify the correct encoding when decoding using different encodings like UTF8, ASCII, or Unicode in the conversion functions.

Decode a Base64 string now , paste it into the free decoder and get the result instantly.
Ishan Karunaratne

Ishan Karunaratne

Software & DevOps engineer

I build and maintain Yo! Base64 Decode and write these guides from hands-on work with encoding in real systems, API payloads, JWTs, CI pipelines, and the occasional 2am debugging session.

More of my writing at techearl.com