To totally unlock this section you need to Log-in
Sometimes you have to create a custom script that requires external files, for example binary dll files or executables. One of the ways you can make sure the script is executed succesfully is by creating a component that first copies the necessary files to the correct locations using the FileCopy action item, but today we are going to show you how to embed a file in a script using base64 encoding.
Encoding the file
The file we want to embed is called AM.dll and is located on our test machine in C:\AM\AM.dll.
To encode the file to base64 we give in the following commands in Powershell prompt:
$Content = Get-Content -Path C:\AM\AM.dll -Encoding Byte $Base64 = [System.Convert]::ToBase64String($Content) $Base64 | Out-File c:\AM\encoded.txt
The result should be a file called encoded.txt in C:\AM.
Open the encoded.txt file and you will see a base64 encoded string representation of the dll file.
Embedding the file
To embed the file, simply create a new variable in your script which contains the base64 string.
$Base64 = "TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..........+DDEAsAA+DDkAsAA+DEEAsAA+DEkAsAA+DFEAsABDDFkAsAA+DGEAsAA+DGkAsAA+DHEAsABIDIEAsABODIkAsAAOAJEA6gYSAJkAAAdTDAkA"
NOTE: The example above has been cropped for readiblity of the blogpost, this should be a rather long string.
Decoding the file
After we have embedded the base64 string representation of the file we need to decode it to a dll file before we can use it.
$Content = [System.Convert]::FromBase64String($Base64) Set-Content -Path $env:temp\AM.dll -Value $Content -Encoding Byte
Now we can use the $env:temp\AM.dll file in the rest of our script, for housekeeping reasons, remove the dll file at the end of the script.
The entire script would look like:
$Base64 = "TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..........+DDEAsAA+DDkAsAA+DEEAsAA+DEkAsAA+DFEAsABDDFkAsAA+DGEAsAA+DGkAsAA+DHEAsABIDIEAsABODIkAsAAOAJEA6gYSAJkAAAdTDAkA" $Content = [System.Convert]::FromBase64String($Base64) Set-Content -Path $env:temp\AM.dll -Value $Content -Encoding Byte #Do your things Remove-Item $env:temp\AM.dll
There you go, a way to embed files in a powershell script, ensuring that the external files the script requires will always be there.
Happy encoding and embedding.