Skip to content

Instantly share code, notes, and snippets.

@nycdotnet
Last active December 5, 2019 16:32
Show Gist options
  • Save nycdotnet/e0c5ac9b1713c8c6808dbd3a331f17a9 to your computer and use it in GitHub Desktop.
Save nycdotnet/e0c5ac9b1713c8c6808dbd3a331f17a9 to your computer and use it in GitHub Desktop.
Embed a file in a PowerShell script
param (
[Parameter(Mandatory=$true)][string]$sourceFile,
[string]$outputFile=""
)
$MAX_LINE_LENGTH = 16000000;
if ($outputFile -eq "") {
$outputFile = '{0}.ps1' -f ($sourceFile)
}
if ($outputFile -eq $sourceFile) {
throw "The source and output file are the same. Cannot proceed as the source file would be overwritten."
}
$bytes = [System.IO.File]::ReadAllBytes($sourceFile);
$b64content = [Convert]::ToBase64String($bytes);
$bytes = $null;
try {
$outputStream = [System.IO.StreamWriter]::new($outputFile)
$writtenByteCount = 0;
$outputStream.Write('$content = ( #{0}{1}' -f (" this array contains the bytes of $sourceFile", "`n"));
while ($writtenByteCount -lt $b64content.Length) {
$take = 0;
if ($writtenByteCount + $MAX_LINE_LENGTH -lt $b64content.Length) {
$take = $MAX_LINE_LENGTH
}
else {
$take = $b64content.Length - $writtenByteCount
}
$buffer = $b64content.Substring($writtenByteCount, $take);
$comma = If ($writtenByteCount + $take -lt $b64content.Length) {","} Else {""};
$outputStream.Write(' "{0}"{1}{2}' -f ($buffer, $comma, "`n"));
$writtenByteCount += $take;
}
$outputStream.Write(');{0}' -f ("`n`n"));
$outputStream.Write('# Uncomment the below two lines to write out the bytes to $destination.{0}' -f ("`n"));
$outputStream.Write('#$destination = "{0}"{1}' -f ($sourceFile, "`n"));
$outputStream.Write('#[System.IO.File]::WriteAllBytes($destination, [Convert]::FromBase64String([String]::Join("",$content)));{0}' -f ("`n"));
}
finally {
$outputStream.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment