Search code examples
arrayspowershell

PowerShell 2 different arrays


I have an $array1 that is docker containers and image names. $array2 is a list of active pull requests from Azure Devops. I have attempted numerous variation of the code below.

I cannot seem to figure out the correct way to items from $array1 if they are not in $array2. Master and Develop must always be removed.

I need all of the items removed from $array1 that are in $array2

$array1 = docker ps -a --no-trunc -f name=myWEAPS* | ForEach-Object { "$(($_ -split '\s+',25)[1,-1])" }
$array1 = $dockerCons[1..($dockerCons.Length - 1)]

$array1 = 'myserver:1517 myserver7998', 'myserver:1515 myserver7990', 'myserver:1514  myserver7999', 'myserver:Master', 'myserverS8003', 'myserver:Develop myserver8002'

$array2 = '1517' , '1518'
$reg = [regex] '[7][0-9][0-9][0-9]'

foreach ($dockerCon in $array1) {
    #Write-Host $dockerCon -ForegroundColor Gray
    if ($array2 -notcontains $dockerCon -and $dockerCon -match $reg) {
        Write-Host "`t"$dockerCon -ForegroundColor Red
    } 
}

Solution

  • Instead of using -notcontains try using -notmatch with a regex OR pattern, -notcontains is specifically to check if an item does not exist in an array but has to be an exact match.

    # adding Develop and Master here since as stated must always be removed
    $array2 = '1517', '1518', 'Develop', 'Master'
    $matchPattern = '7[0-9]{3}'
    # make a regex OR pattern
    $notmatchPattern = $array2 -join '|'
    
    foreach ($dockerCon in $array1) {
        if ($dockerCon -notmatch $notmatchPattern -and $dockerCon -match $matchPattern) {
            Write-Host "`t"$dockerCon -ForegroundColor Red
        }
    }
    

    This would output the following items from $array1:

    myserver:1515 myserver7990
    myserver:1514  myserver7999