在Powershell中编码的命令失败

时间:2016-07-15 02:18:15

标签: powershell

我发现命令编号不好,但我不明白出了什么问题:

我的代码:

$command = "(New-Object System.Net.WebClient).DownloadFile('http://localhost/update_program.exe','updater.exe'); Start-Process 'updater.exe'"
$bytes = [Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
echo $encodedCommand

返回

KABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGU
AbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQARgBpAGwAZQAoACcAaAB0AHQAcAA6AC8ALwBsAG8AYwBhAG
wAaABvAHMAdAAvAHUAcABkAGEAdABlAF8AcAByAG8AZwByAGEAbQAuAGUAeABlACcALAAnAHUAcABkA
GEAdABlAHIALgBlAHgAZQAnACkAOwAgAFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAnAHUAcABk
AGEAdABlAHIALgBlAHgAZQAnAA==

我试试:

powershell -encodedCommand KABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQARgBpAGwAZQAoACcAaAB0AHQAcAA6AC8ALwBsAG8AYwBhAGwAaABvAHMAdAAvAHUAcABkAGEAdABlAF8AcAByAG8AZwByAGEAbQAuAGUAeABlACcALAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnACkAOwAgAFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnAA==

返回:

编者注:以下症状与上述代码不一致,这是正确的。可能没有问题需要解决。

Missing expression after unary operator '-'.
In line: 1 Character: 2
+ - < <<< encodeCommand KABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUA
dAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQARgBpAGwAZQAoACcAaAB0AHQ
AcAA6AC8ALwBsAG8AYwBhAGwAaABvAHMAdAAvAHUAcABkAGEAdABlAF8AcAByAG8AZwByAGEAbQAuAG
UAeABlACcALAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnACkAOwAgAFMAdABhAHIAdAAtAFAAcgBvA
GMAZQBzAHMAIAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnAA==
    + CategoryInfo          : ParserError: (-:String) [], ParentContainsErrorR
   ecordException
    + FullyQualifiedErrorId : MissingExpressionAfterOperator

因为我的命令编码失败了吗?

2 个答案:

答案 0 :(得分:0)

对不起,我想我一开始误解了你的问题。我想你试图询问如何阻止Powershell执行你分配给$ command的字符串。如果是,请尝试以下代码

powershell -command {
    $command = [string] $null; $command += '(New-Object System.Net.WebClient).DownloadFile(';
    $command += "'http://localhost/update_program.exe','updater.exe') ; 
    Start-Process 'updater.exe'"; $bytes = [Text.Encoding]::Unicode.GetBytes($command); 
    $encodedCommand = [Convert]::ToBase64String($bytes); echo $encodedCommand
}

Microsoft希望对变量进行智能处理,以便在变量和函数之间实现更好的兼容性。我认为解析你的命令时会感到困惑。我尝试的是打破字符串赋值,以便Powershell不会认为该字符串是一组指令。上面的单个语句调用Powershell,为$ command指定一个空字符串,两次与Powershell无法混淆的字符串连接,然后在末尾输出$ encodedCommand。这是你追求的吗?

答案 1 :(得分:0)

好的,问题的新答案发生了很大的变化。

尝试

#Encode Command
$command = "(New-Object System.Net.WebClient).DownloadFile('http://localhost/update_program.exe','updater.exe'); Start-Process 'updater.exe'"
$bytes = [Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
echo $encodedCommand

#Execute command
powershell.exe -EncodedCommand $encodedcommand 

只要$command中的陈述正确无误,这就应该有效。