Search code examples
powershellwmiremote-process

Using powershell and wmi to stop and then start a remote process


I'm working on a way to remotely stop and restart a process via PS and WMI. I can easily stop/terminate the process but I'd like to restart the process as well and I'm having issues doing that. Below is the script I use to remotely stop/terminate the process. Any idea what I can add to this that will then restart that same process?

$comp = read-host -Prompt "Enter computer name"
(Get-WmiObject Win32_Process -ComputerName $comp | ?{     $_.ProcessName -match "PhotoScreensaver.scr" }).Terminate()

Solution

  • While I'm certain you could do this with WMI, there's also an easier way. Powershell has a built in cmdlet called Invoke-Command which is for remote code execution. There's also Start-Process and Stop-Process for controlling processes.

    Invoke-Command -ComputerName $Computer -ScriptBlock {
        Start-Process $ProcessName
        Stop-Process $ProcessName
    }
    

    If you're in a domain environment you might have to use the -Authentication Kerberos option to gain rights to the remote computer.

    I'd also like to note that these processes will open in a different session on the remote computer. If a user is logged in, it will not execute in their session. You'd need another tool like PSExec from the SysInternals guys for that.