Search code examples
powershellencodescriptblock

Pass parameter to powershell encoded command


I have a script which has quite a lot of lines. I can easily paste this script in a scriptblock parameter without having to edit it (e.g. put backslashes in front of quotes in the script). I can then encode the script so it can be passed to powershell as en encoded parameter:

$myscript = {
#paste of simplified script
$calc = 6 + 9
echo $calc
}

# Convert script to a string
$command = $carvingScript.ToString()
# Convert string to base64 encoded command
$bytes = [System.Text.Encoding]::Unicode.GetBytes( $command )
$encodedCommand = [Convert]::ToBase64String( $bytes )

I would like to be able to pass one parameter in the script that gets base64 converted. Like this:

$parameter = 9
$myscript = {
$calc = 6 + $parameter
echo $calc
}

Any ideas how to tackle this? I know scriptblock can contain arguments, but in order to parse the argument the whole script needs to be parsed, not just the one parameter


Solution

  • The direct answer to how to add variables to a script block is this:

    $parameter = 9
    
    $myscript = @'
    $calc = 6 + {0}
    echo $calc
    '@ -f $parameter
    
    $scriptblock = [scriptblock]::Create($myscript)
    

    Basically build it as a string and use the create method from [scriptblock] to convert.

    But you can skip creating the scriptblock since you will just convert it back to a string directly afterwards.