I want to run encoded powershell command through System.Diagnostics.Process
#Region successfull test
$Command = {
#$Error.clear()
#[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding( "utf-8" )
write-host 'test'
#Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments
}
$Bytes = [System.Text.Encoding]::Unicode.GetBytes( $Command.ToString() )
$EncodedCommand = [Convert]::ToBase64String( $Bytes )
#endregion
$Arguments = '-Noexit', '-NoLogo', '–NoProfile', '-ExecutionPolicy RemoteSigned', "-EncodedCommand $EncodedCommand"
$Credential = Get-Credential
$DomainAndUserName = $Credential.UserName.Split("\")
$ProcessStartInfoParam = [ordered]@{
Arguments = $Arguments -join ' '
CreateNoWindow = $False
FileName = 'powershell'
WindowStyle = 'Normal'
LoadUserProfile = $False
UseShellExecute = $False
Domain = $DomainAndUserName | Select-Object -first 1
UserName = $DomainAndUserName | Select-Object -last 1
Password = $Credential.Password
}
$ProcessStartInfo = New-Object -TypeName 'System.Diagnostics.ProcessStartInfo' -Property $ProcessStartInfoParam
$Process = New-Object 'System.Diagnostics.Process'
$Process.StartInfo = $ProcessStartInfo
$Process.Start()
Script above work fine and we get test
output.
When i try to modify this script, just add one COMMENTED line
#$Arguments = [System.Management.Automation.PSSerializer]::Deserialize( [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String( $EncodedArguments )) )
in the command scriptblock, for example after write-host 'test'
.
I have failed script with error Exception calling "Start" with "0" argument(s): "The parameter is incorrect."
What happend? Commented line mean nothing.
P.S. Without credential this script work fine.
Run powershell commands is about quoting! just change $arguments
to
$Arguments = '-Noexit', '-NoLogo', '–NoProfile', '-ExecutionPolicy `"RemoteSigned`"', "-EncodedCommand `"$EncodedCommand`""
, add quotation on RemoteSigned and $EncodedCommand. Now its work fine.