我正在尝试执行以下脚本
$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