共用方式為


從執行中的進程譯碼 PowerShell 命令

此範例只會在 Windows 平台上執行。

有時候,您可能會有執行中的PowerShell進程佔用大量資源。 此程式可以在工作排程器工作或 SQL Server Agent 作業的內容中執行。 如果有多個 PowerShell 進程正在執行,可能很難知道哪個進程代表問題。 本文說明如何譯碼 PowerShell 進程目前正在執行的腳本區塊。

建立長時間執行的進程

若要示範此案例,請開啟新的 PowerShell 視窗並執行下列程式代碼。 它會執行 PowerShell 命令,以每隔 10 分鐘輸出一個數位。

powershell.exe -Command {
    $i = 1
    while ( $i -le 10 )
    {
        Write-Output -InputObject $i
        Start-Sleep -Seconds 60
        $i++
    }
}

檢視程式

PowerShell 正在執行的命令主體會儲存在 Win32_Process 類別的 CommandLine 屬性中。 如果命令是編碼的命令, CommandLine 屬性會包含字串 “EncodedCommand”。 使用這項資訊,編碼的命令可以透過下列程序進行反模糊處理。

以 管理員 istrator 啟動 PowerShell。 PowerShell 以系統管理員身分執行非常重要,否則查詢執行中的進程時不會傳回任何結果。

執行下列命令以取得具有編碼命令的所有 PowerShell 進程:

$powerShellProcesses = Get-CimInstance -ClassName Win32_Process -Filter 'CommandLine LIKE "%EncodedCommand%"'

下列命令會建立包含進程標識碼和編碼命令的自定義PowerShell物件。

$commandDetails = $powerShellProcesses | Select-Object -Property ProcessId,
@{
    name       = 'EncodedCommand'
    expression = {
        if ( $_.CommandLine -match 'encodedCommand (.*) -inputFormat' )
        {
            return $matches[1]
        }
    }
}

現在可以譯碼編碼的命令。 下列代碼段會逐一查看命令詳細數據對象、譯碼編碼的命令,並將譯碼的命令新增回 物件以進一步調查。

$commandDetails | ForEach-Object -Process {
    # Get the current process
    $currentProcess = $_

    # Convert the Base 64 string to a Byte Array
    $commandBytes = [System.Convert]::FromBase64String($currentProcess.EncodedCommand)

    # Convert the Byte Array to a string
    $decodedCommand = [System.Text.Encoding]::Unicode.GetString($commandBytes)

    # Add the decoded command back to the object
    $commandDetails |
        Where-Object -FilterScript { $_.ProcessId -eq $currentProcess.processId } |
        Add-Member -MemberType NoteProperty -Name DecodedCommand -Value $decodedCommand
}
$commandDetails[0] | Format-List -Property *

您現在可以選取已譯碼的命令屬性來檢閱譯碼命令。

ProcessId      : 8752
EncodedCommand : IAAKAAoACgAgAAoAIAAgACAAIAAkAGkAIAA9ACAAMQAgAAoACgAKACAACgAgACAAIAAgAHcAaABpAGwAZQAgACgAIAAkAGkAIAAtAG
                 wAZQAgADEAMAAgACkAIAAKAAoACgAgAAoAIAAgACAAIAB7ACAACgAKAAoAIAAKACAAIAAgACAAIAAgACAAIABXAHIAaQB0AGUALQBP
                 AHUAdABwAHUAdAAgAC0ASQBuAHAAdQB0AE8AYgBqAGUAYwB0ACAAJABpACAACgAKAAoAIAAKACAAIAAgACAAIAAgACAAIABTAHQAYQ
                 ByAHQALQBTAGwAZQBlAHAAIAAtAFMAZQBjAG8AbgBkAHMAIAA2ADAAIAAKAAoACgAgAAoAIAAgACAAIAAgACAAIAAgACQAaQArACsA
                 IAAKAAoACgAgAAoAIAAgACAAIAB9ACAACgAKAAoAIAAKAA==
DecodedCommand :
                     $i = 1
                     while ( $i -le 10 )
                     {
                         Write-Output -InputObject $i
                         Start-Sleep -Seconds 60
                         $i++
                     }