How can I get powershell to write þ (lowercase thorn) to a file as 0xfe?

460 views Asked by At

I am attempting to write a PS script that builds and executes a script file for Rocket Software's SBClient. The scripting language uses two different delimiters, þ (lowercase thorn) (0xFE) and ü (u with umlaut) (0xFC).

Each of these gets written to files as two characters. þ is written as þ (A with tilde and 3/4) (0xC3 0xBE). ü gets written as ü (A with tilde and 1/4) (0xC3 0xBC).

I have tried multiple different methods to write the file and it comes up the same way every time. I'm sure this is because these are extended ASCII characters.

Is there a way to write these to a text file with their proper two-character hex codes without converting the string to hex and writing a binary file? If not, what is the best way to convert the string to hex for this? I have seen a few different examples in other languages, but nothing really solid in PS.

It looks like I could convert the string to an array of bytes and then use io.file::WriteAllBytes() to write the file. I was just hoping there was a better way to do this.

Here is the pertinent code...

$ScriptFileContent = 'TUSCRIPTþþþ[Company Name] Logon Please:þ{enter}üPST{enter}þ2þ'
$ScriptFilePath = ([Environment]::GetFolderPath("ApplicationData")).ToString() + "\Rocket Software\SBClient\tuscript\NT"
out-file -filepath $ScriptFilePath -inputobject $ScriptFileContent -encoding ascii

Solution

$enc = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$ScriptFileContent = 'TUSCRIPTþþþ[Company Name] Logon Please:þ{enter}üPST{enter}þ2þ'
$ScriptFileContent = $enc.GetBytes($ScriptFileContent)
$ScriptFilePath = ([Environment]::GetFolderPath("ApplicationData")).ToString() + "\Rocket Software\SBClient\tuscript\NT"
[io.file]::WriteAllBytes($ScriptFilePath, $ScriptFileContent)

Thanks for your help!

1

There are 1 answers

2
Nowhere man On BEST ANSWER

What you're seeing are your chars, outside ASCII, being encoded as UTF-8. You have two choices here:

  • either you use [System.Text.Encoding]::GetEncoding("iso-8859-1") to write your file as Latin1
  • or you use the FileStream.WriteByte() method of the result of io.file.Open to directly write the 0xFE and 0xFC bytes yourself (seems less overkill, but that depends how you write the rest of the data)