Search code examples
windowspowershellpowershell-3.0taskkill

TASKKILL command works properly outside Script, but not inside of it


Few days ago I started developing a Powershell script which monitors a service. Command:

taskkill /f /fi "USERNAME eq admin" /im tm1top.exe

When I ran taskkill to stop one process inside my script it didn’t work: that process remained in Running, hence the script was not able to end properly.

On the other hand, running exactly the same command (taskkill) from CMD directly was successful.

NOTE: the user which is running this script has ADMIN RIGHTS on the computer and I am running Windows Seever 2008. Also tried to create a task into Windows Scheduler and to run it with highest privileges with this user, but the same result..

Could you please advise what should I modify in order to make this function work directly from my ps script?


Solution

  • I would recommend using WMI for this:

    Get-WmiObject Win32_Process | Where-Object {
        $_.GetOwner().User -eq 'admin' -and
        $_.Name -eq 'tm1top.exe'
    } | ForEach-Object {
        $_.Terminate()
    }