1

I am parsing a bunch of data in a textfile. I get the data with Get-Content. Then I loop through each row in $data. Split each row on a space and load those values into an array.

I then loop through each $string in the array.

If the $string matches a specific value I want to delete it out of the array.

$index.Delete(), $index.Remove() does not work, Here is what I have.

$data = Get-Content "C:\Users\$userName\Desktop\test-data.txt"

foreach($row in $data){
    if($row)
    {
        [Array]$index = $row.Split(" ")

        $i = 0 
        foreach($string in $index){

            Write-Host $string 

            if($string -eq "value1" -or $string -eq "value2" -or $string -eq "value3")
            {
                $index.Delete() //This does not work. 
            }
        }

I have also tried something like this as well but it just was not working out at all.

for($i -eq $index.length; $i -le 0; $i++)
{
    Write-Host $index[$i]  #this would hit once then give me an error saying the value is null 

    if($index[$i] -eq "value1" -or $index[$i] -eq "value2" -or $index[$i] -eq "value3")
     {
         $index.Remove()  #does not hit here at all/nor will it work. 
         Write-Host $index
     }
}

How do I remove something from the $index array..?

Is there a better way to do this?

Any help would be much appreciated, thanks.

1
  • Look at this link for a slightly alternative way of achieving this Commented Apr 2, 2014 at 16:31

2 Answers 2

6

The easiest way would be to chain -ne operators:

[Array]$index = $row.Split(" ") -ne $value1 -ne $value2 -ne $value3

Each one will remove all the elements of the array that match the value in the variable, and the result will be passed on to the next. When it's finished, the array will contain the elements the didn't match any of the $value variables.

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

1 Comment

Didn't know this was possible. works exactly how I need it, super easy and very easy to work with. Thank you very much!
-1

Try this:

[array]$index = $row.Split(" ",[stringSplitOptions]::RemoveEmptyEntries) -notmatch "\b(?:$value1|$value2|$value3)\b"

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.