0

I am new to PowerShell and I am stuck with a script to parse CSV document to identify if the emails are in proper format or not. My script does execute but instead of filtering records with invalid email it exports all records with the selected columns.

Please suggest as what I am missing.

$sourceFile = "d:\rvcc.csv"
$targetFile = "d:\LMI-Invalid_Users_{0:yyyyMMMdd-HHmm}.csv" -f (Get-Date)

$validemailDomain1 = "^[a-z]+\.[a-z]+@stu.raritanval.edu$"
$validemailDomain2 = "^[a-z]+@stu.raritanval.edu$"
$validemailDomain3 = "^[a-z0-9]+@stu.raritanval.edu$"
$blankemail=""

Import-CSV $sourceFile | % {
    # The big blue bar:  Or Verbose text: Write-Verbose "Checking:         $($_.EmailAddress)"
    Write-Progress -Activity "Checking user" -Status $_.EmailAddress
    If ($_.EmailAddress -NotMatch $validemailDomain1 -or 
            $_.EmailAddress -NotMatch $validemailDomain2 -or
            $_.EmailAddress -NotMatch $validemailDomain3 -or    
            $_.EmailAddress -NotMatch $blankemail) {
        $_ | Select-Object EmailAddress, FirstName, LastName, UserType, School_Id
    }
} | Export-CSV $targetFile -NoTypeInformation
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • You could simplify your three regex to `^([a-z0-9]|\.)+@stu\.raritanval\.edu$` Notice the escaped periods and simplified first part of expression – RedLaser Jan 08 '16 at 23:17
  • It's _elementary logic_ issue, see [De Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws). You need to use `If ($_ -NotMatch $validemailDomain1 -and $_ -NotMatch $validemailDomain2 -and $_ -NotMatch $validemailDomain3 -and $_ -ne $blankemail)` or @RedLaser's improvement `If ($_ -NotMatch "^([a-z0-9]|\.)+@stu\.raritanval\.edu$" -and $_ -ne $blankemail)`. Note `$_ -ne $blankemail` comparison instead of `$_ -NotMatch $blankemail`. (`$_` used as placeholder for `$_.EmailAddress`) – JosefZ Jan 09 '16 at 01:35

0 Answers0