Search code examples
windowspowershellwmiwin32-process

Script to identify Process Name , Memory , Account Owner in Windows server


I am running a web service in Windows machine , and i wanted to know the Memory used by each user while accessing this Web service. In Task Manager I could see the ProcessName, UserName, Memory. Is there a way to get the same by running powershell or batch script?

Please help.


Solution

  • There's may be a cleaner way to do this, but here's an example:

    $users = @{}
    $process = Get-Process
    
    Get-WmiObject Win32_SessionProcess | ForEach-Object {
    
        $userid = (($_.Antecedent -split “=”)[-1] -replace '"'  -replace “}”,“”).Trim()
        if($users.ContainsKey($userid))
        {
            #Get username from cache
            $username = $users[$userid]
        } 
        else 
        {
            $username = (Get-WmiObject -Query "ASSOCIATORS OF {Win32_LogonSession.LogonId='$userid'} WHERE ResultClass=Win32_UserAccount").Name
            #Cache username
            $users[$userid] = $username
        }
    
        $procid = (($_.Dependent -split “=”)[-1] -replace '"'  -replace “}”,“”).Trim()
        $proc =  $process | Where-Object { $_.Id -eq $procid }
    
        New-Object psobject -Property @{
            UserName = $username
            ProcessName = $proc.Name
            "WorkingSet(MB)" = $proc.WorkingSet / 1MB
        }
    }
    

    OUTPUT:

    UserName ProcessName       WorkingSet(MB)
    -------- -----------       --------------
    Frode    taskhostex                  61,5
    Frode    explorer            172,33203125
    Frode    RuntimeBroker            21,9375
    Frode    HsMgr                   5,578125
    Frode    HsMgr64                 5,453125
    Frode    SetPoint                 17,4375
    

    The code needs to run as admin to get sessions for other users(not just the current user).