Powershell – Decoding a base64 encoded field in a csv with powershell

powershell

Apologies if this a stupid question or I'm asking it in the wrong place.

I have a .csv file with a bunch of network logs in the following format sourceIP,port,destinationIP,port,packetdata. The "packetdata" field contains ASCII information which has been base64 encoded. I need to import the CSV file, convert that single field from base64 back to the original and then export the whole file without touching the other rows.

I know I need to use import-csv to get the data in and I know there's a FromBase64String conversion method but I'm kind of lost.

This is what I have at the moment, which is pretty much hacked together from other code and doesn't actually complete when I try and run it…

import-csv c:\testbase64.csv|foreach-object {$_.packetdata =  [text.encoding]::utf8.getstring([convert]::FromBase64String($_.packetdata))|Export-Csv -Path "C:\outputtest.csv" -NoTypeInformation

[text.encoding]::utf8.getstring([convert]::FromBase64String($variable)) does work if run seperately on the commandline with a standard variable with base64 data in as the data source

I'd appreciate any help anyone can give on this, it would make reading these files much less painful.

Best Answer

Save this as import.ps1 and use as follows: .\import.ps1 C:\test.csv. It will output a CSV in the current directory called Output.csv.

You'll also need to change the Port columns so one is SourcePort and one is DestPort - you can't have 2 columns with the same name when using Import-Csv.

$csv = Import-Csv $args[0]

$csv | ForEach-Object { $_.PacketData = [text.encoding]::utf8.getstring([convert]::FromBase64String($_.PacketData)) }

$csv | Export-Csv "Output.csv" -NoTypeInformation