Niklas Sjögren
Niklas Sjögren

Reputation: 102

Compare 2 arrays with wildcards in powershell

Say we have 2 .txt-files like so:

users.txt

user.name1
user.name2
admin.name1
admin.name2

shares.txt

\\someserver\somefolder\user.name1
\\someserver\somefolder\user.name2
\\someserver\someotherfolder\admin.name1
\\someotherserver\somefolder\admin.name2
\\someplaceelse\somefolder\no.name

I want to compare these 2 points of data to show only the rows in "shares.txt" that match a name in "users.txt". I figure we need to use some sort of wildcardsearch as the username is always included in the uncpath but will not be exactly the same, here is an example of what i have tried so far without success

$users = Get-Content ".\users.txt"
$shares = Get-Content ".\shares.txt"
foreach ($line in $users)
{
if ("*$line*" -like "$shares")
}
Write-Host "this line matches $line"
}
}

Upvotes: 1

Views: 1316

Answers (1)

Edijs Perkums
Edijs Perkums

Reputation: 422

foreach ($line in $users)
{
if ($shares -like "*$line*")
{
Write-Host "$($shares | where {$_ -like "*$line*"}) this line matches $line"
}
}

to get the intended information the current value of the loop must be included in the search.

The problem in your code was that like operator only allows wild cards on the right side of the expression. So the matching must happen the other way around.

Upvotes: 1

Related Questions