Yo! Base64 Encode logoYo! Base64 Encode
PowerShell

How to Base64 Encode Data in PowerShell

Learn to encode data using Base64 in PowerShell with practical examples. Includes string encoding, file handling, and automation scenarios.

By Ishan Karunaratne5 min read

Learn how to encode data to Base64 format using PowerShell. Whether you're working with strings, files, or automation tasks, this guide covers everything you need to know.

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

Quick Start: Basic String Encoding

Here's the simplest way to encode a string in PowerShell:

POWERSHELL
# Basic string encoding
$text = "Hello, World!"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$encoded = [Convert]::ToBase64String($bytes)
Write-Output $encoded  # Output: SGVsbG8sIFdvcmxkIQ==

String Encoding Functions

Create these reusable functions for your scripts:

POWERSHELL
function Convert-ToBase64 {
    param(
        [Parameter(Mandatory=$true)]
        [string]$InputString,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet('UTF8', 'Unicode', 'ASCII')]
        [string]$Encoding = 'UTF8'
    )
    
    try {
        $bytes = [System.Text.Encoding]::$Encoding.GetBytes($InputString)
        $encoded = [Convert]::ToBase64String($bytes)
        
        return @{
            Success = $true
            Encoded = $encoded
            OriginalLength = $InputString.Length
            EncodedLength = $encoded.Length
            Encoding = $Encoding
        }
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
        }
    }
}

# Example usage
$result = Convert-ToBase64 -InputString "Hello, World!" -Encoding "UTF8"
if ($result.Success) {
    Write-Output "Encoded: $($result.Encoded)"
}

File Handling

Encoding Files

POWERSHELL
function Convert-FileToBase64 {
    param(
        [Parameter(Mandatory=$true)]
        [string]$FilePath,
        
        [Parameter(Mandatory=$false)]
        [string]$OutputPath
    )
    
    try {
        # Check if file exists
        if (-not (Test-Path $FilePath)) {
            throw "File not found: $FilePath"
        }
        
        # Read file content
        $bytes = Get-Content $FilePath -Encoding Byte -Raw
        $encoded = [Convert]::ToBase64String($bytes)
        
        # Save to output file if specified
        if ($OutputPath) {
            $encoded | Out-File -FilePath $OutputPath -Encoding UTF8
        }
        
        return @{
            Success = $true
            Encoded = $encoded
            OriginalSize = (Get-Item $FilePath).Length
            EncodedSize = $encoded.Length
            OutputPath = $OutputPath
        }
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
        }
    }
}

# Example usage
$result = Convert-FileToBase64 -FilePath "C:\example.txt" -OutputPath "C:\example.b64"

Processing Large Files

POWERSHELL
function Convert-LargeFileToBase64 {
    param(
        [Parameter(Mandatory=$true)]
        [string]$FilePath,
        
        [Parameter(Mandatory=$true)]
        [string]$OutputPath,
        
        [int]$ChunkSize = 1MB
    )
    
    try {
        $fileStream = [System.IO.File]::OpenRead($FilePath)
        $outputStream = [System.IO.File]::CreateText($OutputPath)
        $buffer = New-Object byte[] $ChunkSize
        $totalBytesRead = 0
        
        while ($bytesRead = $fileStream.Read($buffer, 0, $ChunkSize)) {
            if ($bytesRead -lt $ChunkSize) {
                $buffer = $buffer[0..($bytesRead-1)]
            }
            
            $encoded = [Convert]::ToBase64String($buffer)
            $outputStream.Write($encoded)
            $totalBytesRead += $bytesRead
            
            Write-Progress -Activity "Encoding File" `
                         -Status "Progress: $([math]::Round($totalBytesRead/1MB, 2)) MB" `
                         -PercentComplete (($totalBytesRead/$fileStream.Length) * 100)
        }
        
        return @{
            Success = $true
            TotalBytesProcessed = $totalBytesRead
            OutputPath = $OutputPath
        }
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
        }
    }
    finally {
        if ($fileStream) { $fileStream.Dispose() }
        if ($outputStream) { $outputStream.Dispose() }
    }
}

Automation Scenarios

Batch Processing

POWERSHELL
function Convert-BatchToBase64 {
    param(
        [Parameter(Mandatory=$true)]
        [string]$FolderPath,
        
        [Parameter(Mandatory=$false)]
        [string]$OutputFolder,
        
        [Parameter(Mandatory=$false)]
        [string[]]$FileExtensions = @('.txt', '.log', '.xml')
    )
    
    try {
        # Create output folder if it doesn't exist
        if ($OutputFolder -and -not (Test-Path $OutputFolder)) {
            New-Item -ItemType Directory -Path $OutputFolder | Out-Null
        }
        
        $results = @()
        $files = Get-ChildItem -Path $FolderPath -File | 
                Where-Object { $FileExtensions -contains $_.Extension }
        
        foreach ($file in $files) {
            $outputPath = if ($OutputFolder) {
                Join-Path $OutputFolder "$($file.BaseName).b64"
            } else {
                $null
            }
            
            $result = Convert-FileToBase64 -FilePath $file.FullName -OutputPath $outputPath
            $results += @{
                FileName = $file.Name
                Result = $result
            }
        }
        
        return @{
            Success = $true
            ProcessedFiles = $results
            TotalFiles = $results.Count
            SuccessCount = ($results | Where-Object { $_.Result.Success }).Count
        }
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
        }
    }
}

# Example usage
$batchResult = Convert-BatchToBase64 -FolderPath "C:\InputFiles" -OutputFolder "C:\EncodedFiles"

Network Integration

POWERSHELL
function Send-Base64Data {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Data,
        
        [Parameter(Mandatory=$true)]
        [string]$Url,
        
        [Parameter(Mandatory=$false)]
        [hashtable]$Headers = @{}
    )
    
    try {
        # Encode data
        $encoded = Convert-ToBase64 -InputString $Data
        if (-not $encoded.Success) {
            throw "Encoding failed: $($encoded.Error)"
        }
        
        # Prepare request
        $body = @{
            data = $encoded.Encoded
            timestamp = Get-Date -Format "o"
        } | ConvertTo-Json
        
        # Send request
        $response = Invoke-RestMethod -Uri $Url `
                                    -Method Post `
                                    -Body $body `
                                    -ContentType 'application/json' `
                                    -Headers $Headers
        
        return @{
            Success = $true
            Response = $response
            EncodedLength = $encoded.EncodedLength
        }
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
        }
    }
}

Security Considerations

POWERSHELL
function Protect-Base64Input {
    param(
        [Parameter(Mandatory=$true)]
        [string]$InputString,
        
        [Parameter(Mandatory=$false)]
        [int]$MaxLength = 1MB
    )
    
    try {
        # Input validation
        if ([string]::IsNullOrEmpty($InputString)) {
            throw "Empty input string"
        }
        
        if ($InputString.Length -gt $MaxLength) {
            throw "Input exceeds maximum length"
        }
        
        # Check for potentially malicious content
        $suspiciousPatterns = @(
            '<script',
            'javascript:',
            'vbscript:',
            'data:text/html'
        )
        
        foreach ($pattern in $suspiciousPatterns) {
            if ($InputString -match $pattern) {
                throw "Potentially unsafe content detected"
            }
        }
        
        # Proceed with encoding
        return Convert-ToBase64 -InputString $InputString
    }
    catch {
        return @{
            Success = $false
            Error = $_.Exception.Message
        }
    }
}

Conclusion

PowerShell provides robust capabilities for Base64 encoding through its .NET integration. The functions and examples provided here cover most common scenarios you'll encounter, from simple string encoding to large file processing and automation tasks. Remember to always validate input, handle errors appropriately, and consider security implications when working with encoded data.

Frequently Asked Questions

Q: How do I handle Unicode characters in PowerShell Base64 encoding? A: Use UTF8 or Unicode encoding when converting strings: [System.Text.Encoding]::UTF8.GetBytes($text).

Q: What's the maximum file size I can encode? A: While there's no strict limit, use the Convert-LargeFileToBase64 function with appropriate chunk sizes for large files to manage memory usage.

Q: Can I encode secure strings or credentials? A: Yes, but remember that Base64 is encoding, not encryption. Use SecureString or proper encryption for sensitive data.

Q: How do I handle line breaks in the encoded output? A: PowerShell's Base64 functions handle line breaks automatically, but you can use -NoNewline with Out-File to control output formatting.

Q: Can I use Base64 encoding for automated tasks and scripts? A: Yes, the batch processing and network integration examples show how to integrate Base64 encoding into automated workflows.

Encode text to Base64 now , paste it into the free encoder and get the result instantly.
Ishan Karunaratne

Ishan Karunaratne

Software & DevOps engineer

I build and maintain Yo! Base64 Encode 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