Power Shell Stop-Process 抛出错误,提示进程不存在

Power Shell Stop-Process 抛出错误,提示进程不存在

我正在尝试执行以下脚本

$WonderwareProcess = Get-Process -Name "Studio Manager"
Write-Output $WonderwareProcess
Stop-Process -Name $WonderwareProcess -Force
$Result = Get-Process | Where-Object {$_.HasExited}
Write-Output $Result
Read-Host -Prompt "Press Enter to exit"

它输出以下内容

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                                                                                              
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                                                                                              
    448      83    25776      58408   332     5.68   3264 Studio Manager                                                                                                                                                                                           
Stop-Process : Cannot find a process with the name "System.Diagnostics.Process (Studio Manager)". Verify the process name and call the cmdlet again.
At C:\Users\Winuser\Desktop\Kill Wonderware.ps1:3 char:13
+ Stop-Process <<<<  -Name $WonderwareProcess -Force
    + CategoryInfo          : ObjectNotFound: (System.Diagnost...Studio Manager):String) [Stop-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.StopProcessCommand

为什么 Get-Process 可以找到该进程,而 Stop-Process 却找不到

这是 Windows 7 SP1,带有 Power Shell 2

答案1

您应该将类​​型的值string[]作为cmdlet-NAME的参数传递Stop-Process

(Get-Command Stop-Process).Definition
Stop-Process [-Id] <int[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

Stop-Process -Name <string[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

Stop-Process [-InputObject] <Process[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

否则,PowerShell 会尝试隐式类型转换,例如

  • "$WonderwareProcess"或者
  • [string]$WonderwareProcess或者
  • $WonderwareProcess.ToString()

在您的情况下,任何类型转换都会返回System.Diagnostics.Process (Studio Manager)

使用

  • Stop-Process -Id $WonderwareProcess.Id -Force或者
  • Stop-Process -Name $WonderwareProcess.Name -Force或者
  • Stop-Process -InputObject $WonderwareProcess -Force甚至
  • $WonderwareProcess | Stop-Process -Force

相关内容