697
697

Reputation: 621

Invoke-Command does not kill process on remote machine

Before deployment, I'm trying to kill processes that lock files using PowerShell Invoke-Command

This is my code:

$password = ConvertTo-SecureString "password" -AsPlainText -Force

$credentials = New-Object System.Management.Automation.PsCredential("Admin",$password)

$scriptBlock = {Get-Process | Where-Object { $_.MainWindowTitle -like 'MyApp*'} | Stop-Process}

Invoke-Command -computername Agent1 -Credential $credentials -scriptblock $scriptBlock

Unfortunately it does not do anything and no errors are thrown.

On the machine, this works fine:

Get-Process | Where-Object { $_.MainWindowTitle -like 'MyApp*'} | Stop-Process

Upvotes: 1

Views: 2189

Answers (1)

Moerwald
Moerwald

Reputation: 11274

As described above create a PS session object:

$ErrorActionPreference = "Stop"

$password = ConvertTo-SecureString "password" -AsPlainText -Force

$credentials = New-Object System.Management.Automation.PsCredential("Admin",$password)

$scriptBlock = {
    $process = Get-Process
    $process | Where-Object { $_.MainWindowTitle -like 'MyApp*'} | Stop-Process}
    $process
}
$session = New-PsSession -ComputerName "Agent1" -Credentials $credentials

$remoteProcess = Invoke-Command -Session $session -Credential $credentials -scriptblock $scriptBlock

$remoteProcess | format-table

Above code will also return you a list processes running on the remote host. Based on $remoteProcess you'll see if the process to kill was running or not. I also set the ErrorActionPreference to stop which forces above code to stop on the first error (in case of the session could not be created).

Hope that helps

Upvotes: 1

Related Questions