0

I have an array of elements in PowerShell (v5.1) as below.

I want to remove the item with matching condition EmpId=102

$testData = @(
   @{ Name='ABC'; EmpId=100  },
   @{ Name='EFG'; EmpId=101 },
   @{ Name='XYZ'; EmpId=102 }
);

Is there any simple way to achieve this?

maybe something like $testData.Remove($testData.Find("EmpId == 102")) ?

1
  • is your actual array filled with hashtable items? Commented Dec 11, 2019 at 14:47

2 Answers 2

2

if your array is really a collection of one-item hashtables, then the following otta work ... [grin] it pipes the collection thru the Where-Object cmdlet & filters out anything item that has the value-to-exclude in the EmpId key value.

$TestData = @(
    @{ Name='ABC'; EmpId=100  }
    @{ Name='EFG'; EmpId=101 }
    @{ Name='XYZ'; EmpId=102 }
    )
$EmpId_ToExclude = 102

$TestData |
    Where-Object {
        $_['EmpId'] -ne $EmpId_ToExclude
        }

output ...

Name                           Value
----                           -----
EmpId                          100
Name                           ABC
EmpId                          101
Name                           EFG

note that the items are not required to be in order ... that is how hashtables work if you don't specify [ordered].

Sign up to request clarification or add additional context in comments.

Comments

2

I hope this info is some use. Maybe you can use an arraylist. You don't need @( ) to make an array.

[collections.arraylist]$testData = @{ Name='ABC'; EmpId=100  },
  @{ Name='EFG'; EmpId=101 },
  @{ Name='XYZ'; EmpId=102 }

$a = $testdata[1]
$testdata.remove($a)

Or

$testdata.removeat(1)

Unfortunely, this doesn't work. I guess you would need a pointer to the hashtable:

$testdata.remove(@{ Name='XYZ'; EmpId=102 })

Actually, it would be easy with a single hashtable:

$testData = @{ 'ABC'=100  
  'EFG'=101
  'XYZ'=102 }

$testdata.remove('xyz')

$testdata

Name                           Value
----                           -----
ABC                            100
EFG                            101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.