Sabtu, 01 Oktober 2016

PowerShell v3 Insert Binary Data to ASCII File

I work with large text files on a regular basis. In this case, I needed to generate a header for each file, but, add a small snippet of binary data. The hex characters,  0x0D,0x0A,0x0C, are common control characters. In this case, I needed to add a two line text string, the control characters, then, the remaining content of an original file. My first attempts to add binary data did not fare well, so, I went back to one of my favorite links:
PowerShell Byte Array And Hex Functions
For whatever reason I had never realized the Add-Content cmdlet existed, so, I dug into that one, and, came up with this approach. In the example below I have highlighted the two key lines in yellow.
${C:DataDocuments1.txt} += file 1 content
${C:DataDocuments2.txt} +=
$content = Get-Content -Path $PWD1.txt
$header = file 2 header
[Byte[]] $binaryarray =@(0x0D,0x0A,0x0C);
Add-Content -Path "$pwd2.txt" -Value $header -Encoding Ascii
Add-Content -Path "$pwd2.txt" -Value $binaryarray -Encoding Byte
Add-Content -Path "$pwd2.txt" -Value $content
ii C:DataDocuments2.txt
The real trick here is to use a [Byte[]] array to store your binary string, then, when using Add-Content, be sure to specify -Encoding Byte 

lamsim

About lamsim

Author Description here.. Nulla sagittis convallis. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.

Subscribe to this Blog via Email :