How to get the bytes from a file and convert them to Base64String in PowerShell

Introduction

In this post I’ll share a PowerShell script, that simply reads the bytes from a given file, converts those bytes to a Base64String, and then saves it to a text file.

A little background about why I needed this

I needed to troubleshoot a web service method and I wanted to use SOAP UI as the testing framework. The service method took a byte[] as a parameter and uploaded the corresponding file to a Yammer network.

I’ve been using SOAP UI for testing web services, but most of the times the requests were taking simple types, such as integers and strings. I learned that the way to pass a byte[] to an ASP.NET web service method is to use the Base64String representation, so my next task was to get the Base64String representation of any given file, so I could grab it as simple text and pass it to the XML test request. Rather than creating a console application, I thought that a PowerShell script would get it done faster.

Here is the script

#Get the bytes of a given file
$fileBytes = Get-Content <fileNameAndPath> -Encoding byte

#Convert byte array to base64 string
$fileBytesBase64 = [Convert]::ToBase64String($filebytes)

#Save Base64String to a text file
Add-Content outputFileBytesBase64.txt $fileBytesBase64

Reference

I was able to gather useful tips from these posts:

PowerShell Encoding and Decoding (Base64) – by Sean Metcalf

Efficient Base64 conversion in PowerShell – by mnaoumov

Author: Luis Carrazana

Skilled Senior Technology Consultant and Strategist, with 15+ of experience advising and assisting customers from small and large companies from multiple industries, including Pharma, Insurance and Financial Services. Leveraging the right technology for the right job. Passionate about Software Craftsmanship, Quality, Agile, DevOps and Cloud Computing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s