I'm attempting to kill a parent process and it's child process (There will only be one child) on a remote computer. When executing this script (Which is part of a larger one) i get the following error. PowerShell Newbie, so any suggestions for improvement beyond solving the error are most welcome.
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
Script:
$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
Best Answer
The error your getting is because the following line is improperly expressed:
The error is trying (in microsoft fashion) to tell you that it needs a script block after a
ForEach
. Replace the line with the following to continue past that error:Also, just an aside, but powershell does not require line terminators unless you're processing multiple commands on the same line in the shell. In short, you don't need to end every line with
;
.