Tuesday, March 23, 2010

Powershell: Find Process User name without using WMI

function get-ProcUser ([System.String] $procname)
{
    if (!$procname) {return "Provide some process name"}
    $proclist=get-process $procname.trim() -ErrorAction silentlycontinue
    if(!$proclist -and ($procname.contains("."))){
        $proclist=get-process $procname.split(".")[0].trim() -ErrorAction silentlycontinue
    }
    if(!$proclist) {return "Provide some proper process name"}

    foreach($proc in $proclist)
    {
        $procprop=tasklist /V /FO List /FI ("PID eq "+$proc.id)
        foreach ($field in $procprop)
        {
               if ($field -match "user name")
              {
                      $field.split(":")[1].trim()
               }
        }
    }
}

I have tried to handle the minimal errors here. You can add more if you wish.

Parameter can be made to pass id also, but that won’t be too useful.

Error handling is in small fonts.

Checked only on Windows 7 RTM x64. ErrorAction may not be valid on V1.

Tried hard on C#, but could not find any options.

Versions of Installed applications

gwmi -query "Select name,version from Win32_Product" | format-table name,version

image

PS is running as administrator.

No comments: