Powershell how to remove redundency in a n arraylist
I have the global arraylist "$global:processid", which has many processid-entries and $globale:processname, which has all the processes that belongs to the ids. sometimes all the entries the $global:processid arraylist got, are the same. how can i loop through the two arraylists and delete all duplicated processids and there processnames. I got the following code now. But i don't have this filtering. [System.Collections.ArrayList]$global:processname = @() [System.Collections.ArrayList]$global:processid = @()
for ($i = 0; $i -lt $global:processid.Count; $i++) {
"Position "+$i+": "+$global:processid[$i]
#$lvi = [System.Windows.Forms.ListViewItem]::new()
#$lvi.Text = $global:processname[$i]
#$lvi.SubItems.Add($global:processid[$i])
#$global:ListviewOCLRA.Items.Add($lvi)
}
It is important that the it will be checked for duplicated processids and delete the processnae at this position. For instance if the positions 3-7 are the same entries again and again in the $global:processid arraylist, all the entries at positions 3-7 in the arraylist $global:processname should also be deleted.
I hope u understand what i mean. Thx for the help.
Although as commented, it would be best to use one single array containing objects, you can still create such an array using your two arraylists, as long as they are still intact and where each index can get you the id and a matching process name
Assume your arrays are like this:
$processid = 123, 456, 123
$processname = 'notepad', 'powershell', 'notepad'
As you can see, there's a duplicate in there
Join these arrays while their indices still match the name and id into one single array of objects
$processes = for ($i = 0; $i -lt $processid.Count; $i++) {
[PsCustomObject]@{ Id = $processid[$i]; Name = $processname[$i] }
}
Now you can eliminate the duplicate objects based on the ID property
$processes | Sort-Object -Property Id -Unique
$processes
now contains:
ID Name
-- ----
123 notepad
456 powershell
Next, fill your listview
for ($i = 0; $i -lt $processes.Count; $i++) {
$lvi = [System.Windows.Forms.ListViewItem]::new()
$lvi.Text = $processes[$i].Name
$lvi.SubItems.Add($processes[$i].Id)
$ListviewOCLRA.Items.Add($lvi)
}