idarryl
idarryl

Reputation: 769

remove item from system.array in PowerShell

This is my $array:

Name          GUID 
----          ---- 
PC001         AAAA 
PC001         BBBB 
PC001         CCCC 
PC002         AAAA
PC002         DDDD
PC003         AAAA
PC003         CCCC

Here's my script:

$Guid = "CCCC"
$workingName = $array | where Guid -eq $Guid | select  name
$array.remove($workingName) #broke!

What I'm trying to achieve is that if $Guid = "CCCC" it would remove all instances of the Name and CCCC from the array, where CCCC exists, so in this instance five lines (three lines for PC001, two lines for PC0003), if it was BBBB it would only remove the three lines for PC001.

FYI: this is part of a much larger script

Upvotes: 1

Views: 1585

Answers (2)

DanL
DanL

Reputation: 2024

$Guid = "CCCC"
$workingName = $array | where Guid -eq $Guid | select -ExpandProperty name
$array = $array | where { $_.name -notin $workingName }

Upvotes: 0

Noah Sparks
Noah Sparks

Reputation: 1762

Well, you could create a new variable or just update the exiting one using a where statement.

$Array | ? {$_.GUID -ne 'CCCC'}

This will return the array back without the entries

Alternatively you can use methods, like you are trying to do there but you need to build the array a bit differently...here is an example.

$Proc = Get-Process | Select -first 2
$a = New-Object System.Collections.ArrayList
$a.Add($Proc[0])
$a.Add($Proc[1])
$a
Write-Warning 'removing index 1'
$a.remove($Proc[1])
$a

Upvotes: 4

Related Questions