Code
$FilePath = 'c:\temp\test.csv'
# Use the file path in your script
$Entry = Get-Content -Path $FilePath -raw
$Entry = $Entry -split "\r?\n"
# Initialize the $Result array
$Result = @()
# Loop through each email address in the array
foreach ($Email in $Entry) {
$ValidEmail = $null
$Value = $null
# Remove leading and trailing spaces, and replace middle spaces with dots
$Value = $Email.Trim() -replace '\s+', '.'
try {
# Try to create a new mail address object to validate the address
$ValidEmail = (New-Object System.Net.Mail.MailAddress $Value).Address
}
catch {
# If there is an exception, ignore it and move on to the next validation method
# Try to extract the email address from a display name format
if ($Value -match '(?<!<)(?<Email>\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b)(?!>)') {
$ValidEmail = $matches['Email']
}
else {
# If all else fails, try to form a valid address by stripping and adding
$ValidEmail = ($Value -replace '[<>,()@,]', '' -replace '\s+', '.' -replace '[^A-Za-z0-9._%+-]+', '') + '@Domain.com'
}
}
# Add the valid email address to the $Result array
$Result += $ValidEmail
}
# Return the valid email addresses
return $Result
When I run above in VSCode and pause on the line $Entry = $Entry -split "\r?\n"
The answer is correct
If I close vscode, open it and run the script with no debug the answer is wrong.
Test data
Mark Gonzalez
Dan.Ca@domain.com
Jennifer Zal <jennifer.zal@domain.com>
Debug answer
Mark.Gonzalez@domain.com
Dan.Ca@domain.com
Jennifer.Zald@domain.com
Script just run
Mark.Gonzalez.Dan.Ca@domain.com.Jennifer.Zal