Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

How to create byte array in PowerShell

To create a byte array in PowerShell, you can use several methods, depending on whether you want to initialize it with values, specify a size, or convert data like a string or file. The simplest method is to cast an array to the [byte[]] type.

1. Create a byte array with pre-defined values

This is the most common and direct approach. You cast a comma-separated list or a range of integers to [byte[]]. All values must be between 0 and 255. 

# Cast a comma-separated list of integers
[byte[]]$byteArray = 10, 20, 30, 40, 100

# Cast a range of integers using the range operator (..)
[byte[]]$byteArrayFromRange = 1..5

# Cast and assign directly
$otherByteArray = [byte]1, 2, 3, 4, 5

A byte array ([byte[]]) is a fundamental data structure used in programming to represent a sequence of bytes (8-bit values). Its primary uses include:

  1. Network Communications: Data sent and received over networks (like downloading a file from the web) is often transmitted as streams of bytes, which are captured in byte arrays.

  2. Binary Data Handling: It's the primary way to handle raw binary data that isn't meant to be interpreted as text. This is crucial because not all files are text files (e.g., images, executables, compressed archives, documents).

  3. Interoperability and Low-Level Operations: When working with low-level Windows API functions or .NET libraries that deal with memory buffers, you often need to pass data as a byte array.

  4. File I/O Operations: Reading from or writing to binary files (like reading an image into memory or writing a downloaded file to disk) is done using byte arrays.

  5. Encoding Strings: Converting text strings to and from their byte representations (using encodings like UTF-8, ASCII) for storage or transmission is done with byte arrays.

  6. Cryptography and Hashing: Algorithms that encrypt, decrypt, or compute hashes (like SHA256) almost always operate on byte arrays.

To view the data type of the variable, use .GetType():

$byteArray.GetType().Name
# Output: Byte[]
2. Create an empty or zero-initialized byte array
You can create a byte array of a specific size that is initialized with zeroes. 
#Create a zero-initialized array of a specific size
$emptyArray = [byte[]]::new(5)
$emptyArray[0] # This will be 0
$emptyArray.Length # This will be 5

# Example with New-Object
$anotherEmptyArray = New-Object byte[] 5

3. Convert a string to a byte array

Use the System.Text.Encoding class to convert a string into a byte array, specifying the desired character encoding (e.g., UTF8, ASCII, Unicode). 

# Create a string
$string = "Hello, world!"

# Convert the string to a byte array using UTF8 encoding
$byteArrayFromText = [System.Text.Encoding]::UTF8.GetBytes($string)

# View the resulting byte array
$byteArrayFromText
# Output: 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33

################################################################################

# Convert a string to a UTF-8 encoded byte array
[byte[]]$stringBytes = [System.Text.Encoding]::UTF8.GetBytes("Hello World")
$stringBytes

# Convert it back to a string to verify
[System.Text.Encoding]::UTF8.GetString($stringBytes)

4. Read file contents into a byte array

When working with binary files (like images, archives, or executables), use Get-Content with the -AsByteStream or -Encoding Byte parameter. The -Raw parameter is also often used to ensure the entire file is read as a single stream. 
 
For PowerShell 6 and later, use -AsByteStream:
# Read a binary file into a byte array in PowerShell 6+
$byteArrayFromFile = Get-Content -Path "C:\Temp\file.zip" -AsByteStream -Raw

For older versions of Windows PowerShell, use -Encoding Byte

# Read a binary file into a byte array in older Windows PowerShell
$byteArrayFromFile = Get-Content -Path "C:\Temp\file.zip" -Encoding Byte -Raw

# Read a file's contents directly into a byte array - For PowerShell v5.1 and below
$bytesFromFile = Get-Content -Path "C:\Temp\image.jpg" -Encoding Byte

Alternatively, you can use the .NET [System.IO.File] class, which is cross-compatible with all versions of PowerShell:

# Use the .NET Framework method
$byteArrayFromFile = [System.IO.File]::ReadAllBytes("C:\Temp\file.zip")

Important Note on the [byte] Type

A [byte] can only hold values from 0 to 255. If you try to assign a number outside this range, you will get an error.

# This will WORK
[byte]$validByte = 200

# This will FAIL with an error
[byte]$invalidByte = 300

Useful Articles
How to Resize Azure Virtual Machines using PowerShell Script
HTML JavaScript generate GUID
Generate GUID using PowerShell GUI tool
PowerShell Generate GUI guid form windows form wpf

Get Nutanix virtual machine details using PowerShell #AHV #AOS
From Manual to Automated - Managing Dell iDRAC Power via Redfish API and PowerShell
Turn Your PowerShell Into a Web Server: Instantly Share Local HTML & Files!
Monitoring Dell Server Health Using RACADM CLI: Sensor Info from iDRAC
PowerShell Create and Export Self-Signed RSA Certificates (PFX, CER, PEM)
Automate Intune MDM Device Sync: A PowerShell Script for Microsoft Graph API
Streamlining Intune MDM Device Management with Microsoft Graph and PowerShell
PowerShell & Microsoft Graph API: Automate Full Intune Devices Sync more than 1000 Pagination

Go Back

Comment

Protected by Mathcha

Blog Search

Page Views

1 4 6 4 5 8 3 9

Archive

Follow me on Blogarama