Powershell

使用 Powershell 殺死遠端上的父子程序

  • November 16, 2015

我試圖殺死一個父程序,它是遠端電腦上的子程序(只有一個子程序)。執行此腳本(這是較大腳本的一部分)時,我收到以下錯誤。PowerShell 新手,因此非常歡迎任何除解決錯誤之外的改進建議。

Cannot bind parameter 'Process'. Cannot convert the "Kill-ChildProcess" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
       + CategoryInfo          : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
       + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand

腳本:

$scriptBlock =  {                 
       function Kill-ChildProcess(){
           param($ID=$PID)
               $CustomColumnID = @{
               Name = 'Id'
               Expression = { [Int[]]$_.ProcessID }
               }

               Write-Host $ID
               $result = Get-WmiObject -Class Win32_Process -Filter "ParentProcessID=$ID" |
               Select-Object -Property ProcessName, $CustomColumnID, CommandLine

               $result | Where-Object { $_.ID -ne $null } | Stop-Process
       }


        Get-Process $args[0] -ErrorAction SilentlyContinue | ForEach Kill-ChildProcess -id {$_.ID};
        Get-Process $args[0] -ErrorAction SilentlyContinue | Stop-Process -ErrorAction SilentlyContinue;
   };


Invoke-Command -Session $session  -ArgumentList $processToKill -ScriptBlock $scriptBlock

您得到的錯誤是因為以下行表達不正確:

Get-Process $args[0] -ErrorAction SilentlyContinue | ForEach Kill-ChildProcess -id {$_.ID};

該錯誤試圖(以微軟方式)告訴您它需要在ForEach. 用以下內容替換該行以繼續克服該錯誤:

Get-Process $args[0] -ErrorAction SilentlyContinue | ForEach {Kill-ChildProcess -id $_.ID}

另外,順便說一句,除非您在 shell 的同一行上處理多個命令,否則 powershell 不需要行終止符。簡而言之,您不需要以;.

引用自:https://serverfault.com/questions/736761