3

I'm using PowerShell to upload files to a web site through an API.

In PS5.1, this would get the image in the correct B64 encoding to be processed by the API at the other end:

$b64 = [convert]::ToBase64String((get-content $image_path -encoding byte))

In PS7, this breaks with the error:

Get-Content: Cannot process argument transformation on parameter 'Encoding'. 'byte' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. (Parameter 'name')

I've tried reading the content in other encoding then using [system.Text.Encoding]:GetBytes() to convert, but the byte array is always different. Eg

PS 5.1> $bytes = get-content -Path $image -Encoding byte ; Write-Host "bytes:" $bytes.count ; Write-Host "First 11:"; $bytes[0..10] 
bytes: 31229
First 11:
137
80
78
71
13
10
26
10
0
0
0

But on PowerShell7:

PS7> $enc = [system.Text.Encoding]::ASCII
PS7> $bytes = $enc.GetBytes( (get-content -Path $image -Encoding ascii | Out-String)) ; Write-Host "bytes:" $bytes.count ; Write-Host "First 11:"; $bytes[0..10]
bytes: 31416   << larger
First 11:
63 << diff
80 << same
78 << 
71
13
10
26
13 << new
10
0
0

I've tried other combinations of encodings without any improvement. Can anyone suggest where I'm going wrong?

EnterpriseMike
  • 165
  • 2
  • 7

2 Answers2

10

With PowerShell 6 Byte is not a valid argument for the Enconding-Parameter anymore. You should try the AsByteStream-Parameter in combination with the Parameter Raw like so:

$b64 = [convert]::ToBase64String((get-content $image_path -AsByteStream -Raw))

There is even an example in the help for Get-Content that explains how to use these new parameters.

Peter M.
  • 686
  • 1
  • 5
  • 17
4

The problem turned out to be with Get-Content. I bypassed the problem using:

$bytes = [System.IO.File]::ReadAllBytes($image_path)

NOTE: the $image_path needs to be absolute, not relative.

So my Base64 line became:

$b64 = [convert]::ToBase64String([System.IO.File]::ReadAllBytes($image_path))
EnterpriseMike
  • 165
  • 2
  • 7