0

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
dcaz
  • 847
  • 6
  • 15

1 Answers1

2
  • There's no obvious explanation for your symptom; on a general note, a notable pitfall when using the PIC (PowerShell Integrated Console) in Visual Studio Code is that state can linger between runs, potentially affecting subsequent runs - unless you configure the PIC to start a new, temporary session for each debugging run - see this answer.

  • I suggest streamlining your code as follows, which not only improves its efficiency, but may make the problem go away:

$FilePath = 'c:\temp\test.csv'

# This outputs the modified lines directly.
Get-Content $FilePath |
  ForEach-Object {
    $addr = $_ -replace '^.*<|>.*$'
    try {
      ([System.Net.Mail.MailAddress] $addr).Address
    } catch {
      $addr.Trim() -replace '[^a-z0-9._%+-]' -replace '\s+', '.'
    }
  }
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • i have been thinking that maybe i need to produce a new variable here `$Entry = $Entry -split "\r?\n"` but I don't know why? I will look at what you wrote. – dcaz Mar 09 '23 at 17:46
  • Error: `Method invocation failed because [System.Net.Mail.MailAddress] does not contain a method named 'TryCreate'` – dcaz Mar 09 '23 at 17:47
  • 1
    @dcaz, I didn't realize that `::TryCreate()` works in [_PowerShell (Core) 7+_](https://github.com/PowerShell/PowerShell/blob/master/README.md) only. Please see my update, which shows a solution that works in both PowerShell editions. – mklement0 Mar 09 '23 at 17:56