Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Filtering an array by another [filter] array if any part of the text matches.

Tags:

powershell

Okay, I'm still fairly new to PowerShell.

I've written a piece of code that works, but it smells entirely wrong. What is the right way to write this from a PowerShell standpoint?

$filters = @("*a*","*b*")
$data = @("c/a","c/b","c/a/d","e","a","e/f")
$desiredResults = @("e","e/f")

Write-Host "Filters" -ForegroundColor Yellow
$filters 
Write-Host "Data" -ForegroundColor Yellow
$data

$results = @()

foreach ($d in $data)
{
    [bool] $skip = $false
    foreach ($filter in $filters)
    {
        if ($d -like $filter)
        {
            $skip = $true
        }
    }

    if ($skip -eq $false)
    {
        $results += $d
    }
}

Write-Host "Desired Results" -ForegroundColor Yellow
$desiredResults
Write-Host "Results" -ForegroundColor Yellow
$results
like image 976
Jason V Avatar asked Jan 27 '26 04:01

Jason V


1 Answers

you can do like this

$filters = @("a","b")
$data = @("c/a","c/b","c/a/d","e","a","e/f")
$desiredResults = @("e","e/f")

$data | Select-String -Pattern $filters -NotMatch
like image 195
Chandan Rai Avatar answered Jan 30 '26 16:01

Chandan Rai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!