Split returns and chat GCP understanding



$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
Jennifer Zal <jennifer.zal@domain.com>

Debug answer


Script just run


>Solution :

  • 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 runsunless 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+', '.'

Leave a Reply Cancel reply