With Powershell, how can I get the id of a process owned by a specific user?

8,362

Solution 1

I found this with a quick google:

$owners = @{}
gwmi win32_process |% {$owners[$_.handle] = $_.getowner().user}

get-process | select processname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}}

seems to return users as requested. You can probably proceed from there. Hope that helps.

Solution 2

With PowerShell 4 and newer you can do:

Get-Process -IncludeUserName | Where-Object {$_.UserName -match "peter" -and $_.ProcessName -eq "Notepad"} | Stop-Process -Force

or when using aliases:

ps -IncludeUserName | ? {$_.UserName -match "peter" -and $_.ProcessName -eq "Notepad"} | spps -Force

not as short as in Unix but better than in older PowerShell versions.

Share:
8,362

Related videos on Youtube

Andrew J. Brehm
Author by

Andrew J. Brehm

Not a penguin and not a Linux user either.

Updated on September 17, 2022

Comments

  • Andrew J. Brehm
    Andrew J. Brehm over 1 year

    Using Powershell, I want to do the equivalent of Unix

    ps -auxc | grep Emacs
    
    kill -9 364
    

    (Assuming 365 was the pid the first command told me.)

    How do I do that? I find it incredibly hard to get Powershell to tell me the owner of a process and the way I tried, getting a wmi-object win32_process and then make that into a list of processes named "explorer.exe" just started lots of explorer.exe instances.

  • Andrew J. Brehm
    Andrew J. Brehm about 13 years
    Isn't it amazing how easy and simple Powershell is compared to the old out-dated Unix shells? :-)