読者です 読者をやめる 読者になる 読者になる

Powershellで実行中のプロセスを取得・分析する

Windows上で実行中のプロセスを取得・分析する方法について。

1. 動作確認環境

2. プロセス一覧を取得する

単純に実行中のプロセス一覧を取得する場合、以下の2つの方法があります。

  1. "Get-Process"コマンドレットで取得
  2. WMI(Win32_Process)で取得

上記2つの結果はそれぞれ異なるため、用途に合わせて使い分ける必要があります。
具体的に結果がどう異なるかは以下に記載します。

(1)"Get-Process"でプロセス一覧を取得した場合

以下の通り、Get-Processの返却値は"System.Diagnostics.Process"型になります。
メソッドやプロパティの詳細はMSDNを参照してください。
Process クラス (System.Diagnostics)

PS > Get-Process | Get-Member | ft -Wrap


   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize
PM                         AliasProperty  PM = PagedMemorySize
VM                         AliasProperty  VM = VirtualMemorySize
WS                         AliasProperty  WS = WorkingSet
Disposed                   Event          System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Object,
                                          System.Diagnostics.DataReceivedEventArgs)
Exited                     Event          System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Object,
                                           System.Diagnostics.DataReceivedEventArgs)
BeginErrorReadLine         Method         void BeginErrorReadLine()
BeginOutputReadLine        Method         void BeginOutputReadLine()
CancelErrorRead            Method         void CancelErrorRead()
CancelOutputRead           Method         void CancelOutputRead()
Close                      Method         void Close()
CloseMainWindow            Method         bool CloseMainWindow()
CreateObjRef               Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                    Method         void Dispose(), void IDisposable.Dispose()
Equals                     Method         bool Equals(System.Object obj)
GetHashCode                Method         int GetHashCode()
GetLifetimeService         Method         System.Object GetLifetimeService()
GetType                    Method         type GetType()
InitializeLifetimeService  Method         System.Object InitializeLifetimeService()
Kill                       Method         void Kill()
Refresh                    Method         void Refresh()
Start                      Method         bool Start()
ToString                   Method         string ToString()
WaitForExit                Method         bool WaitForExit(int milliseconds), void WaitForExit()
WaitForInputIdle           Method         bool WaitForInputIdle(int milliseconds), bool WaitForInputIdle()
__NounName                 NoteProperty   System.String __NounName=Process
BasePriority               Property       int BasePriority {get;}
Container                  Property       System.ComponentModel.IContainer Container {get;}
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;set;}
ExitCode                   Property       int ExitCode {get;}
ExitTime                   Property       datetime ExitTime {get;}
Handle                     Property       System.IntPtr Handle {get;}
HandleCount                Property       int HandleCount {get;}
HasExited                  Property       bool HasExited {get;}
Id                         Property       int Id {get;}
MachineName                Property       string MachineName {get;}
MainModule                 Property       System.Diagnostics.ProcessModule MainModule {get;}
MainWindowHandle           Property       System.IntPtr MainWindowHandle {get;}
MainWindowTitle            Property       string MainWindowTitle {get;}
MaxWorkingSet              Property       System.IntPtr MaxWorkingSet {get;set;}
MinWorkingSet              Property       System.IntPtr MinWorkingSet {get;set;}
Modules                    Property       System.Diagnostics.ProcessModuleCollection Modules {get;}
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize {get;}
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize64 {get;}
PagedMemorySize            Property       int PagedMemorySize {get;}
PagedMemorySize64          Property       long PagedMemorySize64 {get;}
PagedSystemMemorySize      Property       int PagedSystemMemorySize {get;}
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64 {get;}
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;}
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {get;}
PeakVirtualMemorySize      Property       int PeakVirtualMemorySize {get;}
PeakVirtualMemorySize64    Property       long PeakVirtualMemorySize64 {get;}
PeakWorkingSet             Property       int PeakWorkingSet {get;}
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {get;set;}
PriorityClass              Property       System.Diagnostics.ProcessPriorityClass PriorityClass {get;set;}
PrivateMemorySize          Property       int PrivateMemorySize {get;}
PrivateMemorySize64        Property       long PrivateMemorySize64 {get;}
PrivilegedProcessorTime    Property       timespan PrivilegedProcessorTime {get;}
ProcessName                Property       string ProcessName {get;}
ProcessorAffinity          Property       System.IntPtr ProcessorAffinity {get;set;}
Responding                 Property       bool Responding {get;}
SessionId                  Property       int SessionId {get;}
Site                       Property       System.ComponentModel.ISite Site {get;set;}
StandardError              Property       System.IO.StreamReader StandardError {get;}
StandardInput              Property       System.IO.StreamWriter StandardInput {get;}
StandardOutput             Property       System.IO.StreamReader StandardOutput {get;}
StartInfo                  Property       System.Diagnostics.ProcessStartInfo StartInfo {get;set;}
StartTime                  Property       datetime StartTime {get;}
SynchronizingObject        Property       System.ComponentModel.ISynchronizeInvoke SynchronizingObject {get;set;}
Threads                    Property       System.Diagnostics.ProcessThreadCollection Threads {get;}
TotalProcessorTime         Property       timespan TotalProcessorTime {get;}
UserProcessorTime          Property       timespan UserProcessorTime {get;}
VirtualMemorySize          Property       int VirtualMemorySize {get;}
VirtualMemorySize64        Property       long VirtualMemorySize64 {get;}
WorkingSet                 Property       int WorkingSet {get;}
WorkingSet64               Property       long WorkingSet64 {get;}
PSConfiguration            PropertySet    PSConfiguration {Name, Id, PriorityClass, FileVersion}
PSResources                PropertySet    PSResources {Name, Id, Handlecount, WorkingSet, NonPagedMemorySize, PagedMemo
                                          rySize, PrivateMemorySize, VirtualMemorySize, Threads.Count, TotalProcessorTi
                                          me}
Company                    ScriptProperty System.Object Company {get=$this.Mainmodule.FileVersionInfo.CompanyName;}
CPU                        ScriptProperty System.Object CPU {get=$this.TotalProcessorTime.TotalSeconds;}
Description                ScriptProperty System.Object Description {get=$this.Mainmodule.FileVersionInfo.FileDescripti
                                          on;}
FileVersion                ScriptProperty System.Object FileVersion {get=$this.Mainmodule.FileVersionInfo.FileVersion;}
Path                       ScriptProperty System.Object Path {get=$this.Mainmodule.FileName;}
Product                    ScriptProperty System.Object Product {get=$this.Mainmodule.FileVersionInfo.ProductName;}
ProductVersion             ScriptProperty System.Object ProductVersion {get=$this.Mainmodule.FileVersionInfo.ProductVer
                                          sion;}
(2)WMI(Win32_Process)でプロセス一覧を取得した場合

以下の通り、WMI(Win32_Process)の返却値は"System.Management.ManagementObject#root\cimv2\Win32_Process"型になります。
メソッドやプロパティの詳細はMSDNを参照してください。
Win32_Process class (Windows)

PS > Get-WmiObject Win32_Process | Get-Member


   TypeName: System.Management.ManagementObject#root\cimv2\Win32_Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
ProcessName                AliasProperty  ProcessName = Name
PSComputerName             AliasProperty  PSComputerName = __SERVER
VM                         AliasProperty  VM = VirtualSize
WS                         AliasProperty  WS = WorkingSetSize
AttachDebugger             Method         System.Management.ManagementBaseObject AttachDebugger()
GetOwner                   Method         System.Management.ManagementBaseObject GetOwner()
GetOwnerSid                Method         System.Management.ManagementBaseObject GetOwnerSid()
SetPriority                Method         System.Management.ManagementBaseObject SetPriority(System.Int32 Priority)
Terminate                  Method         System.Management.ManagementBaseObject Terminate(System.UInt32 Reason)
Caption                    Property       string Caption {get;set;}
CommandLine                Property       string CommandLine {get;set;}
CreationClassName          Property       string CreationClassName {get;set;}
CreationDate               Property       string CreationDate {get;set;}
CSCreationClassName        Property       string CSCreationClassName {get;set;}
CSName                     Property       string CSName {get;set;}
Description                Property       string Description {get;set;}
ExecutablePath             Property       string ExecutablePath {get;set;}
ExecutionState             Property       uint16 ExecutionState {get;set;}
Handle                     Property       string Handle {get;set;}
HandleCount                Property       uint32 HandleCount {get;set;}
InstallDate                Property       string InstallDate {get;set;}
KernelModeTime             Property       uint64 KernelModeTime {get;set;}
MaximumWorkingSetSize      Property       uint32 MaximumWorkingSetSize {get;set;}
MinimumWorkingSetSize      Property       uint32 MinimumWorkingSetSize {get;set;}
Name                       Property       string Name {get;set;}
OSCreationClassName        Property       string OSCreationClassName {get;set;}
OSName                     Property       string OSName {get;set;}
OtherOperationCount        Property       uint64 OtherOperationCount {get;set;}
OtherTransferCount         Property       uint64 OtherTransferCount {get;set;}
PageFaults                 Property       uint32 PageFaults {get;set;}
PageFileUsage              Property       uint32 PageFileUsage {get;set;}
ParentProcessId            Property       uint32 ParentProcessId {get;set;}
PeakPageFileUsage          Property       uint32 PeakPageFileUsage {get;set;}
PeakVirtualSize            Property       uint64 PeakVirtualSize {get;set;}
PeakWorkingSetSize         Property       uint32 PeakWorkingSetSize {get;set;}
Priority                   Property       uint32 Priority {get;set;}
PrivatePageCount           Property       uint64 PrivatePageCount {get;set;}
ProcessId                  Property       uint32 ProcessId {get;set;}
QuotaNonPagedPoolUsage     Property       uint32 QuotaNonPagedPoolUsage {get;set;}
QuotaPagedPoolUsage        Property       uint32 QuotaPagedPoolUsage {get;set;}
QuotaPeakNonPagedPoolUsage Property       uint32 QuotaPeakNonPagedPoolUsage {get;set;}
QuotaPeakPagedPoolUsage    Property       uint32 QuotaPeakPagedPoolUsage {get;set;}
ReadOperationCount         Property       uint64 ReadOperationCount {get;set;}
ReadTransferCount          Property       uint64 ReadTransferCount {get;set;}
SessionId                  Property       uint32 SessionId {get;set;}
Status                     Property       string Status {get;set;}
TerminationDate            Property       string TerminationDate {get;set;}
ThreadCount                Property       uint32 ThreadCount {get;set;}
UserModeTime               Property       uint64 UserModeTime {get;set;}
VirtualSize                Property       uint64 VirtualSize {get;set;}
WindowsVersion             Property       string WindowsVersion {get;set;}
WorkingSetSize             Property       uint64 WorkingSetSize {get;set;}
WriteOperationCount        Property       uint64 WriteOperationCount {get;set;}
WriteTransferCount         Property       uint64 WriteTransferCount {get;set;}
__CLASS                    Property       string __CLASS {get;set;}
__DERIVATION               Property       string[] __DERIVATION {get;set;}
__DYNASTY                  Property       string __DYNASTY {get;set;}
__GENUS                    Property       int __GENUS {get;set;}
__NAMESPACE                Property       string __NAMESPACE {get;set;}
__PATH                     Property       string __PATH {get;set;}
__PROPERTY_COUNT           Property       int __PROPERTY_COUNT {get;set;}
__RELPATH                  Property       string __RELPATH {get;set;}
__SERVER                   Property       string __SERVER {get;set;}
__SUPERCLASS               Property       string __SUPERCLASS {get;set;}
ConvertFromDateTime        ScriptMethod   System.Object ConvertFromDateTime();
ConvertToDateTime          ScriptMethod   System.Object ConvertToDateTime();
Path                       ScriptProperty System.Object Path {get=$this.ExecutablePath;}

3. プロセスを実行中のユーザ一覧を取得する

現在プロセスを実行しているユーザの一覧を取得したい場合は、WMI(Win32_Process)を用いて、以下の様に実現可能です。

PS > Get-WmiObject Win32_Process | Group-Object {$_.getowner().Domain},{$_.getowner().User} | Sort-Object Count -Descending | ft -Wrap

Count Name                      Group
----- ----                      -----
   20 NT AUTHORITY, SYSTEM      {\\testserver\root\cimv2:Win32_Process.Handle="252", \\testserver\root\cimv2:Win32_Process.Handle
                                ="352", \\testserver\root\cimv2:Win32_Process.Handle="416", \\testserver\root\cimv2:Win32_Process
                                .Handle="424"...}
   10 CONTOSO, Administrator    {\\testserver\root\cimv2:Win32_Process.Handle="2476", \\testserver\root\cimv2:Win32_Process.Handl
                                e="572", \\testserver\root\cimv2:Win32_Process.Handle="1048", \\testserver\root\cimv2:Win32_Proce
                                ss.Handle="2996"...}
    5 NT AUTHORITY, NETWORK SER {\\testserver\root\cimv2:Win32_Process.Handle="692", \\testserver\root\cimv2:Win32_Process.Handle
      VICE                      ="60", \\testserver\root\cimv2:Win32_Process.Handle="1916", \\testserver\root\cimv2:Win32_Process
                                .Handle="2744"...}
    3 NT AUTHORITY, LOCAL SERVI {\\testserver\root\cimv2:Win32_Process.Handle="876", \\testserver\root\cimv2:Win32_Process.Handle
      CE                        ="952", \\testserver\root\cimv2:Win32_Process.Handle="588"}
    2                           {\\testserver\root\cimv2:Win32_Process.Handle="0", \\testserver\root\cimv2:Win32_Process.Handle="
                                4"}
    1 Window Manager, DWM-1     {\\testserver\root\cimv2:Win32_Process.Handle="784"}


Win32_Processクラスでは、"getowner"メソッドを用いて、各プロセス実行ユーザのドメイン名とユーザ名を取得可能です。

上記の例では、"Group-Object"コマンドレットにて"ドメイン名($_.getowner().Domain)+ユーザ名($_.getowner().User)"を軸にグループ化し、更に"Sort-Object"コマンドレットで実行プロセス数が多い順に降順で表示するようにしています。

その他

他にも、メモリ使用量順にプロセスを並べ替えて表示するなど、様々な切り口で情報取得・分析が可能です。また、分析結果に応じて、特定プロセスの優先度を上げ下げすることもできます。