Reputation: 39
I have a CSV file of 2000 email addresses. I am using PowerShell to check if the user is active in AD. Another developer wrote a PowerShell script for me to do this but he only used the main domain for the email format to match, he didn't add the subdomian that it could have. Some of our email addresses have a 3 part email address after the @ symbol.
For example, his code:
foreach ($user in $users) {
Write-Host $user.email
if ($user.email -match "\@mycompany\.com$") {
$status = "NOT FOUND"
# loop through possible AD domains until there is a hit
foreach ($domain in "na","au","eu","as") {
if ($status -eq "NOT FOUND") {
Write-Host " $($domain)" -NoNewline
$status = Get-UserFromEmail -EMail $user.email -ADDomain $domain
Write-Host $status
}
else {
break
}
}
Write-Host
Add-Content -Path $outcsv -Value "$($user.email),$($user.type),`"$($status)`""
}
else {
Add-Content -Path $outcsv -Value "$($user.email),$($user.type),NOT MYCOMPANY"
}
What I need to be able to do is get the match to check if it is a two or three part email address. @consultant.mycompany.com or @mycompany.com.
Any insight for this PowerShell newbie would be appreciated.
Upvotes: 0
Views: 916
Reputation: 7489
here is one way to test for membership in more than one email domain. all of the domains are all in the same example.com
, but they could easily be in testing.com
or wizbang.org
.
this demos the idea, i presume you can insert it into your script as needed. [grin]
what it does ...
$
to the end of each escaped string to anchor the pattern to the end of the email addressthe code ...
$EmailList = @(
'[email protected]'
'[email protected]'
'[email protected]'
'[email protected]'
'[email protected]'
)
$DomainList = @(
'@example.com'
'@more.example.com'
'@even.more.example.com'
)
$Regex_DL = $DomainList.ForEach({
[regex]::Escape($_) + '$'
}) -join '|'
$ValidEmailAddressList = $EmailList -match $Regex_DL
$ValidEmailAddressList
output ...
[email protected]
[email protected]
[email protected]
[email protected]
Upvotes: 1
Reputation: 175065
You can always use the -or
operator to chain multiple expressions inside the if
condition:
if ($user.email -match "\@mycompany\.com$" -or $user.email -match '@consultant\.mycompany\.com$'){
# ...
}
Alternatively, you can construct a regex pattern that'll match both:
if($user.email -match '@(?:consultant\.)?mycompany\.com$'){
# ...
}
If you're ever unsure about how to escape a literal string in a reguar expression, use [regex]::Escape()
:
PS C:\> [regex]::Escape('@consultant.mycompany.com')
@consultant\.mycompany\.com
Upvotes: 0