EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Base64
 

PowerShell Base64

Updated March 6, 2023

PowerShell Base64

 

 

Introduction to PowerShell Base64

PowerShell Base64 is a technique or mechanism that is used to encode and decode data. The encoding and decoding are important in order to prevent the data from malware attacks. Base64 encoding and decoding is a popular method to encrypt and decrypt the data. As the name suggests, there will be 64 characters in Base64 string. It is a combination of upper case, lower case and numbers along with a maximum of two equal sign at the end.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax:

The following are the syntax of Base64 encoding and decoding:

Encoding:

[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("TextToEncode"))

Decoding:

[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String(texttobedecoded'))

Examples of PowerShell Base64

Given below are the examples of PowerShell Base64:

Example #1

Code:

Encoding:

$input = ‘text to be encoded’
$By = [System.Text.Encoding]::Unicode.GetBytes($input)
$output =[Convert]::ToBase64String($By)
$output

Output:

PowerShell Base64 op 1

Decoding:

$input = “vikivikivikivikivikivyapvyapvyapvyapvyapnandnandnandnandnandviki”
$output = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($input))
$output

Output:

Decoding

Example #2

Encoding and decoding a file.

Code:

clear-host
Write-Host "Welcome to the example of powershell base64 encoding and decoding" -ForegroundColor Green
Write-Host "Encoding of a text file"
# Encoding a file content
$inputfile = "C:\Vignesh\Names.txt"
$fc = get-content $inputfile
$By = [System.Text.Encoding]::UTF8.GetBytes($fc)
$etext = [System.Convert]::ToBase64String($By)
Write-Host "ENCODED text file content is " $etext -ForegroundColor Green
# Decoding a file content
Write-Host "Decoding the above converted text"
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($etext)) | Out-File -Encoding "ASCII" c:\vignesh\decoded.txt
$outfile123 = get-content c:\vignesh\decoded.txt
Write-Host "Decoded text is as follows" -ForegroundColor Green
Write-Host "DECODED: " $outfile123

Output:

PowerShell Base64 op 3

Example #3

Code:

clear-host
Write-Host "Demo of Encoding and decoding of an exe file" -ForegroundColor Green
Write-Host "Encoding of an exe file" -ForegroundColor Green
# Encode
$fp = "C:\Vignesh\helloworld.exe"
$encf = [System.IO.File]::ReadAllBytes($fp);
# returns the base64 string
$b64str = [System.Convert]::ToBase64String($encf);
Write-Host "After encoding" -ForegroundColor Green
$b64str
# Decode
#function to decode
function Convert-stob {
[CmdletBinding()] param (
[string] $estr
, [string] $fp = (‘{0}\{1}’ -f $env:TEMP, [System.Guid]::NewGuid().ToString())
)
try {
if ($estr.Length -ge 1) {
Write-Host "After decoding of exe" -ForegroundColor Green
# decodes the base64 string
$barr = [System.Convert]::FromBase64String($estr);
[System.IO.File]::WriteAllBytes($fp, $barr);
Write-Host $barr
}
}
catch {
}
Write-Output -InputObject (Get-Item -Path $fp);
}
$DecodedFile = Convert-stob -estr $b64str -fp C:\Vignesh\helloworld.exe

Output:

PowerShell Base64 op 4

PowerShell Base64 op 5

Example #4

Decoding an image file.

Code:

Write-Host "Encoding an image file"
#function to encode to base64
function ctob64
{
[CmdletBinding()] param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] [ValidateScript({ Test-Path -Path $_ })] [String]$fp
)
Write-Host "Encoding the image file" -ForegroundColor Green
[System.convert]::ToBase64String((Get-Content -Path $fp -Encoding Byte))
}
#decode function of an image file
function cfb64
{
[CmdletBinding()] param (
[parameter(Mandatory = $true, ValueFromPipeline)] [String]$str
)
try
{
Write-Host "Decoding image file" -ForegroundColor Green
[System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String($str))
}
catch
{
Write-Host "Error occurred" -ForegroundColor Red
$Error[0].Exception.Message
}
}

Output:

Decoding an image file

PowerShell Base64 op 7

Example #5

Code:

function Testhex
{
[CmdletBinding()] Param
(
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [Alias("FN","FP")] $pa,
[Int] $wd = 16,
[Int] $co = -1,
[String] $ph = ".",
[Switch] $noo,
[Switch] $not
)
Write-Host "Demo of encoding to hex values" -ForegroundColor Green
$lc = 0
get-content $pa -encoding by -readcount $wd -totalcount $co |
foreach-object `
{
$pad = $txt = $null
$bys = $_
foreach ($by in $bys)`
{
$byh = [String]::Format("{0:X}", $by)
$pad += $byh.PadLeft(2,"0") + " "
}
if ($pad.length -lt $width * 5)
{ $pad = $pad.PadRight($width * 5," ") }
foreach ($by in $bys)`
{
if ( [Char]::IsLetterOrDigit($by) -or
[Char]::IsPunctuation($by) -or
[Char]::IsSymbol($by) )
{ $txt += [Char] $by }
else
{ $txt += $placeholder }
}
$ottt = [String]::Format("{0:X}", $lc)
$ottt = $ottt.PadLeft(8,"0") + "h:"
$lc += $width # Increment lc.
if (-not $noo) { $pad = "$ottt $pad" }
if (-not $not) { $pad = $pad + $txt }
Write-Host "Hex decimal values" -ForegroundColor Green
$pad
}
}
Testhex C:\Vignesh\helloworld.exe

Output:

PowerShell Base64 op 8

Example #6

Code:

function encodecsv{
[CmdletBinding()] param (
[Parameter(Mandatory=$True)] [string] $fn
)
Write-Host "encoding a csv file using base64" -ForegroundColor Green
if (Test-Path "$fn"){
$ct = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.IO.File]::ReadAllText("$fn")))
Write-Host "encoded output is below" -ForegroundColor Green
return $fn, $ct
}
throw "File not found $fn"
}
#Example
encodecsv C:\Vignesh\Sample.csv

Output:

PowerShell Base64 op 9

Example #7

Code:

Add-Type -AssemblyName System.Web
Write-Host "Demo of encoding and decoding urls using base64"
Write-Host "Example of encoding url"
$testurl="https://test.test.com/test/TestSite1/Shared/"
Write-Host "url before encoding " $testurl -ForegroundColor Green
#The below code is used to encode the URL
Write-Host "encoding url...."
$utoe = $testurl
$res = [System.Web.HttpUtility]::UrlEncode($utoe)
Write-Host "after encoding,the url is" $res -ForegroundColor Green
#decoding url.
$utod = $res
Write-Host "Decoding the above encoded url" -ForegroundColor Green
$dcu = [System.Web.HttpUtility]::UrlDecode($utod)
Write-Host "after decoding, the url is " $dcu -ForegroundColor Green
#Decode URL code ends here.

Output:

Demo of encoding and decoding urls

Example #8

Code:

Write-Host "Demo of encoding a pdf file" -ForegroundColor Green
Write-Host "Read the pdf" -ForegroundColor Green
Write-Host "After encoding" -ForegroundColor Green
$pdffile = Get-Content "C:\Vignesh\Vyapini Birth Certificate.pdf"‬
$bytestest = [System.Text.Encoding]::ASCII.GetBytes($pdffile)
$base641 =[Convert]::ToBase64String($bytestest)

Output:

Demo of encoding a pdf file

Conclusion

Thus, the article shows in detail about the Base64 encoding technique in PowerShell. It showed various examples of encoding and decoding various file type, strings, pdf file, csv file etc.

Recommended Articles

This is a guide to PowerShell Base64. Here we discuss the introduction and examples of PowerShell Base64 for better understanding. You may also have a look at the following articles to learn more –

  1. PowerShell Sleep
  2. PowerShell SubString
  3. PowerShell not like
  4. Else If in PowerShell

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW