powershell

How to convert String System Object into a Byte System Array in powershell?


I would like to create a binary blob from a binary character string, in the same way as when reading in a binary blob from a file, into a buffer, using .NET file stream. Then I would like to read 2 bytes from a particular offset in blob.

I create a file like this:

echo "AAAABBBB" > .\zzblob.txt 
$bytes = "AAAABBBB`r`n"
$aa = [system.bitconverter]::touint16($bytes, 0)

# FAIL!

# Checking the type:
$bytes.GetType() | select Name, BaseType | ft -HideTableHeaders

# String System.Object

Now, doing the same using a stream buffer, we get something else.

$fp = ".\zzblob.txt"
$bf = (new-object byte[](256))
$sp = New-Object System.IO.FileStream($fp, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$sp.Length
$sp.Read($bf, 0, 256)
$sp.close()

$aa = [system.bitconverter]::touint16($bf, 2)   # ..AA
d2h $aa
# 0x4141  ## OK!

# Checking type:
$bf.GetType() | select Name, BaseType | ft -HideTableHeaders

# Byte[] System.Array

How can I convert a string from String System.Object to Byte[] System.Array?


Solution


  • [1] The ISO-88591 encoding that -Encoding Latin1 refers to is closely related to, but not identical to Windows-1252, so using the latter - which -Encoding Default may refer to in Windows PowerShell, depending on the system locale (e.g. on US-English and Western European machines) - is not an option.