EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Base64
Secondary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Interview Questions
    • PowerShell Interview Questions

PowerShell Base64

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.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

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

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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*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?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more