If your script requires external binary resources such as picture files or DLLs, you can of course ship them together with your script. You could, however, also embed these binaries as text in your script files:
- Read the binary files as bytes
- Save the bytes as Base64-encoded strings
This way, your script can then read the Base64-encoded binaries from a text variable, turn the data back into bytes, and write them back into temporary files.
Here are two simple functions that illustrate the concept:
function Convert-BinaryToText { param ( [Parameter(Mandatory)] [string] $Path ) $Bytes = [System.IO.File]::ReadAllBytes($Path) [System.Convert]::ToBase64String($Bytes) } function Convert-TextToBinary { param ( [Parameter(Mandatory)] [string] $Text, [Parameter(Mandatory)] [string] $OutputPath ) $Bytes = [System.Convert]::FromBase64String($Text) [System.IO.File]::WriteAllBytes($OutputPath, $Bytes) }
Convert-BinaryToText takes a path to any file and returns the Base64-encoded string. Convert-TextToBinary does the opposite: submit the Base64-encoded string plus a destination path, and the function recreates the binary file.
Note that saving a binary file as Base64-string isn’t exactly space conserving. Your script is likely to grow in size beyond the original binary file size. However, even though the Base64-encoded strings are large, PowerShell handles them well, and extracting a binary file from Base64-encoded strings is very fast.