Tim
Tim

Reputation: 21

Match two get-process variables isnt working

with my code I want to get the ProcessID of a programm called VNCviewer, then I open up a new session in this programm at this point I've got the ProcessID of the Overview console and a opened Session without knowing the ProcessID (both tasks are named the same). Now I want to find the ProcessID of the new Session to get this I did the loop to match both processID and kill the one which isnt the one saved in my first variable but its not working I'm getting the error that the variable "PID" is read only. Someone has a solution for me?

$NVCOverview = Get-Process vncviewer
$wshell = New-Object -ComObject wscript.shell;
start-sleep -Milliseconds 1000

(New-Object -ComObject WScript.Shell).AppActivate((get-process vncviewer).MainWindowTitle)
Start-Sleep -Milliseconds 100
$wshell.SendKeys("{TAB}")
Start-Sleep -Milliseconds 100
$wshell.SendKeys("{TAB}")
Start-Sleep -Milliseconds 100
$wshell.SendKeys("{ENTER}")

Start-Sleep -Milliseconds 5000

$newVncProcesses = get-process vncviewer | where {$_.Id -NotLike $NVCOverview[0]}

foreach ($pid in $newVncProcesses)
{
    Stop-Process $pid
}

I expect that the loop will catch the ID of the neweset Session and kills it.

Upvotes: 1

Views: 58

Answers (1)

PMental
PMental

Reputation: 1188

$PID is a reserved automatic variable in Powershell that holds the Process ID of the current Powershell session, and therefore read-only like the message suggests.

Change $pid to $id or something like that and it should work like expected.

See more about the many automatic variables in the documentation, some can be quite useful.

EDIT: Your filter is a bit off too, you're comparing only the Id property of the current object to the whole object of the original variable, and using an index of zero that doesn't make sense for a variable containing a single process. This:

$newVncProcesses = get-process vncviewer | where {$_.Id -NotLike $NVCOverview[0]}

should probably look more like this:

$newVncProcesses = get-process vncviewer | where {$_.Id -ne $NVCOverview.Id}

Upvotes: 2

Related Questions