Steve
Steve

Reputation: 347

PowerShell String Array Pattern Matching

I have a PowerShell query.

I have the below 2 string arrays. What I want to be able to do is to return only those entries from $RecycleBinPaths that do not begin with all the entries from $ExcludeRecycleBinsPathWildCards (i.e. Wildcard pattern match)

$RecycleBinPaths = @('C:\$Recycle.Bin','D:\$RECYCLE.BIN','E:\$RECYCLE.BIN','F:\$RECYCLE.BIN','L:\$RECYCLE.BIN','M:\$RECYCLE.BIN','S:\$RECYCLE.BIN','T:\$RECYCLE.BIN')

$ExcludeRecycleBinsPathWildCards = @('C:\','F:\')

In the above example I want the output to be:

D:\$RECYCLE.BIN
E:\$RECYCLE.BIN
L:\$RECYCLE.BIN
M:\$RECYCLE.BIN
S:\$RECYCLE.BIN
T:\$RECYCLE.BIN

In fact $ExcludeRecycleBinsPathWildCards array above can contain any number of entries, not necessarily just 2 as shown above.

Are you able to help? Thanks.

Upvotes: 1

Views: 387

Answers (2)

Venkataraman R
Venkataraman R

Reputation: 12959

Another way of looping through the items and adding to another array.

$RecycleBinPaths = @('C:\$Recycle.Bin','D:\$RECYCLE.BIN','E:\$RECYCLE.BIN','F:\$RECYCLE.BIN','L:\$RECYCLE.BIN','M:\$RECYCLE.BIN','S:\$RECYCLE.BIN','T:\$RECYCLE.BIN')

$ExcludeRecycleBinsPathWildCards = @('C:\','F:\')

$SelectedRecycleBinPaths = @()

foreach($rbp in $RecycleBinPaths)
{

    if(-Not ($ExcludeRecycleBinsPathWildCards -contains $rbp.ToString().Substring(0,3)))
    {
        $SelectedRecycleBinPaths += $rbp
    }

} 

$SelectedRecycleBinPaths
D:\$RECYCLE.BIN
E:\$RECYCLE.BIN
L:\$RECYCLE.BIN
M:\$RECYCLE.BIN
S:\$RECYCLE.BIN
T:\$RECYCLE.BIN

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

Use nested .Where() methods:

$RecycleBinPaths.Where({
  # Save path to separate variable
  $path = $_
  # Now test if _any_ string in the list of wildcards match, and then apply -not - making it resolve to true only if _none_ of the wildcards match the path
  -not $ExcludeRecycleBinsPathWildCards.Where({ $path -like "$_*" }, 'First')
})

Upvotes: 2

Related Questions