Home > other >  Pass complex arguments to powershell script through encoded command
Pass complex arguments to powershell script through encoded command

Time:07-07


I want to run nested powershell script block, with complex type arguments. I want to pass parameters to powershell scriptblock trough encoded command and encoded arguments. I`m trying this script.
$text = "This is a test message."
$Cred = get-credential 'alex'
$Arguments = @{
    Msg  = $Text
    Proc = $PID
    Cred = $Cred
}

$Serialized       = [System.Management.Automation.PSSerializer]::Serialize($Arguments)
$Bytes            = [System.Text.Encoding]::Unicode.GetBytes($Serialized)
$EncodedArguments = [Convert]::ToBase64String($Bytes)

$ScriptBlock = {
    param([String]$Base64)
    $Serialized = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Base64))
    $Arguments  = [System.Management.Automation.PSSerializer]::Deserialize($Serialized)

    Write-Host " $($Arguments.msg) FROM PID: $($Arguments.proc), cred: $( $Arguments.Cred.Username)"
}

$Bytes          = [System.Text.Encoding]::Unicode.GetBytes( $ScriptBlock.ToString() )
$EncodedCommand = [Convert]::ToBase64String( $Bytes )

Start-Process -FilePath powershell -ArgumentList '-noprofile', '-noexit', `
'-EncodedCommand', $EncodedCommand, '-EncodedArguments', $EncodedArguments

Powershell process flashing, then closing. Help me to correct this script.
PS. Why stack overflow editor replace the header of my message 'Hello team!' ? Its all right on preview.

CodePudding user response:

A -EncodedArguments parameter (or something alike) doesn't exist, therefore I would simply embed your arguments as a default param value in your (encoded) scriptblock:

$Arguments = @{
    Msg  = "This is a test message."
    Proc = $PID
    Cred = (Get-Credential 'Alex')
}

$Serialized       = [System.Management.Automation.PSSerializer]::Serialize($Arguments)
$Bytes            = [System.Text.Encoding]::Unicode.GetBytes($Serialized)
$EncodedArguments = [Convert]::ToBase64String($Bytes)

$ScriptBlock = "param([String]`$EncodedArguments = '$EncodedArguments')"   {
    $Serialized = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($EncodedArguments))
    $Arguments  = [System.Management.Automation.PSSerializer]::Deserialize($Serialized)

    Write-Host " $($Arguments.msg) FROM PID: $($Arguments.proc), cred: $( $Arguments.Cred.Username)"
}

$Bytes          = [System.Text.Encoding]::Unicode.GetBytes( $ScriptBlock.ToString() )
$EncodedCommand = [Convert]::ToBase64String( $Bytes )

Start-Process -FilePath powershell -ArgumentList '-noprofile', '-noexit', '-EncodedCommand', $EncodedCommand
  • Related