【问题标题】:Invoke-Command does not kill process on remote machineInvoke-Command 不会杀死远程机器上的进程
【发布时间】:2019-05-17 02:06:49
【问题描述】:

在部署之前,我正在尝试使用 PowerShell Invoke-Command 杀死锁定文件的进程

这是我的代码:

$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

不幸的是,它什么也没做,也没有抛出任何错误。

在机器上,这工作正常:

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

【问题讨论】:

  • 如果有一个进程在后台运行,那么它不会有一个窗口标题。尝试Enter-PSSession -computername Agent1,然后执行Get-Process -IncludeUsername | Where-Object { $_.MainWindowTitle } 你应该得到一个空的结果,即使你通过 RDP 登录到 Agent1 并启动记事本或其他东西,如果你尝试通过远程会话列出它,你仍然不会得到任何结果。
  • 我试图杀死的进程正在作为控制台应用程序运行,并且标题与我的停止进程脚本中的标题匹配。使用完全相同的命令,在 Agent1 机器上,我可以杀死它,运行:Get-Process | Where-Object { $_.MainWindowTitle -like 'MyApp*'} |停止进程我已经尝试过 Enter-PSSession -computername Agent1 -credential $credentials 它工作得很好,但是一样。运行命令没有结果。
  • 所以如果我理解正确,它可以使用Enter-PSSession,是吗?尝试使用New-PSSession 创建一个会话对象,然后将该对象传递给Enter-PSSession 并进行测试;如果可行,请尝试将会话对象传递给Invoke-Command
  • 我可以连接到机器,但是当我尝试真正停止那里的任何进程时,它没有..

标签: powershell


【解决方案1】:

如上所述创建一个PS会话对象:

$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

上面的代码还会返回一个远程主机上运行的进程列表。根据$remoteProcess,您将看到要终止的进程是否正在运行。我还将ErrorActionPreference 设置为stop,这会强制上述代码在出现第一个错误时停止(以防无法创建会话)。

希望有帮助

【讨论】:

  • $session = New-PsSession -ComputerName "Agent1" -Credentials $credentials - 应该是 -Credential $credentials (小错字,额外的 's') 但是,在此之后: $remoteProcess = Invoke-命令 -Session $session -scriptblock $scriptBlock $remoteProcess |格式表 - 这执行但没有结果,进程仍在运行
  • 我认为这可能是您需要做的。 stackoverflow.com/questions/958123/…
  • 使用 Get-Process | Where-Object { $_.MainWindowTitle -like 'MyApp*' 不起作用,显然是因为访问 UI 的运气。然而Stop-Process -Name "cmd*" -Force 在我的情况下完成了这项工作,即使它不是我想要的。谢谢大家的帮助!
猜你喜欢
  • 2014-11-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多