从正在运行的进程解码 PowerShell 命令Decode a PowerShell command from a running process
本文内容
有时,您可能必须运行的进程什么占用了大量的资源的 PowerShell。可能的上下文中运行此过程任务计划程序作业或SQL Server 代理作业。其中有多个运行的 PowerShell 进程,它可能很难知道哪个进程表示问题。本文介绍如何对 PowerShell 进程当前正在运行的脚本块。
创建长时间运行进程Create a long running process
为了演示此方案中,打开新的 PowerShell 窗口并运行下面的代码。它将执行的 PowerShell 命令的输出 10 分钟内每隔一分钟的数字。
1. powershell.exe -Command {
2. $i = 1
3. while ( $i -le 10 )
4. {
5. Write-Output -InputObject $i
6. Start-Sleep -Seconds 60
7. $i++
8. }
9. }
查看进程View the process
执行的 PowerShell 命令的正文存储在CommandLine的属性Win32_Process类。如果该命令是编码命令,则CommandLine属性包含字符串"EncodedCommand"。使用此信息,该编码的命令可以是通过以下过程取消模糊处理。
以管理员身份启动 PowerShell。非常重要,以管理员身份运行 PowerShell,否则不返回任何结果查询正在运行的进程时。
执行以下命令获取所有已编码的命令的 PowerShell 进程:
1. $powerShellProcesses = Get-CimInstance -ClassName Win32_Process -Filter 'CommandLine LIKE "%EncodedCommand%"'
以下命令创建包含进程 ID 和编码命令的自定义 PowerShell 对象。
1. $commandDetails = $powerShellProcesses | Select-Object -Property ProcessId,
2. @{
3. name = 'EncodedCommand'
4. expression = {
5. if ( $_.CommandLine -match 'encodedCommand (.*) -inputFormat' )
6. {
7. return $matches[1]
8. }
9. }
10. }
现在可以解码已编码的命令。以下代码片段循环访问命令的详细信息对象、 解码已编码的命令,并将解码后的命令添加回以便进一步进行调查的对象。
1. $commandDetails | ForEach-Object -Process {
2. # Get the current process
3. $currentProcess = $_
5. # Convert the Base 64 string to a Byte Array
6. $commandBytes = [System.Convert]::FromBase64String($currentProcess.EncodedCommand)
8. # Convert the Byte Array to a string
9. $decodedCommand = [System.Text.Encoding]::Unicode.GetString($commandBytes)
11. # Add the decoded command back to the object
12. $commandDetails |
13. Where-Object -FilterScript { $_.ProcessId -eq $_.ProcessId } |
14. Add-Member -MemberType NoteProperty -Name DecodedCommand -Value $decodedCommand
15. }
16. $commandDetails[0]
现在可以选择已解码的 command 属性来查看已解码的命令。
1. ProcessId : 8752
2. EncodedCommand : IAAKAAoACgAgAAoAIAAgACAAIAAkAGkAIAA9ACAAMQAgAAoACgAKACAACgAgACAAIAAgAHcAaABpAGwAZQAgACgAIAAkAGkAIAAtAG
3. wAZQAgADEAMAAgACkAIAAKAAoACgAgAAoAIAAgACAAIAB7ACAACgAKAAoAIAAKACAAIAAgACAAIAAgACAAIABXAHIAaQB0AGUALQBP
4. AHUAdABwAHUAdAAgAC0ASQBuAHAAdQB0AE8AYgBqAGUAYwB0ACAAJABpACAACgAKAAoAIAAKACAAIAAgACAAIAAgACAAIABTAHQAYQ
5. ByAHQALQBTAGwAZQBlAHAAIAAtAFMAZQBjAG8AbgBkAHMAIAA2ADAAIAAKAAoACgAgAAoAIAAgACAAIAAgACAAIAAgACQAaQArACsA
6. IAAKAAoACgAgAAoAIAAgACAAIAB9ACAACgAKAAoAIAAKAA==
7. DecodedCommand :
8. $i = 1
10. while ( $i -le 10 )
12. {
14. Write-Output -InputObject $i
16. Start-Sleep -Seconds 60
18. $i++
20. }
