Email Validation Toolkit

# Email Validation Toolkit

# Function to validate email using a simple regex pattern
function Test-EmailSimple {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Email
    )
    
    $regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    return $Email -match $regex
}

# Function to validate email using a more comprehensive regex pattern
function Test-EmailComprehensive {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Email
    )
    
    $regex = "^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"
    return $Email -match $regex
}

# Function to validate email with domain check
function Test-EmailWithDomain {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Email
    )
    
    $regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    if ($Email -match $regex) {
        $domain = ($Email -split "@")[1]
        if (Resolve-DnsName -Name $domain -ErrorAction SilentlyContinue) {
            return $true
        }
    }
    return $false
}

# Function to validate multiple emails
function Test-MultipleEmails {
    param (
        [Parameter(Mandatory=$true)]
        [string[]]$Emails,
        [Parameter(Mandatory=$false)]
        [ValidateSet("Simple", "Comprehensive", "WithDomain")]
        [string]$Method = "Simple"
    )
    
    $results = @()
    foreach ($email in $Emails) {
        switch ($Method) {
            "Simple" { $isValid = Test-EmailSimple -Email $email }
            "Comprehensive" { $isValid = Test-EmailComprehensive -Email $email }
            "WithDomain" { $isValid = Test-EmailWithDomain -Email $email }
        }
        $results += [PSCustomObject]@{
            Email = $email
            IsValid = $isValid
        }
    }
    return $results
}

# Function to extract emails from text
function Get-EmailsFromText {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Text
    )
    
    $regex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
    return $Text | Select-String -Pattern $regex -AllMatches | ForEach-Object { $_.Matches.Value }
}

# Example usage
$testEmails = @(
    "user@example.com",
    "invalid.email@",
    "another.user@example.co.uk",
    "not_an_email"
)

Write-Host "Simple Validation:"
Test-MultipleEmails -Emails $testEmails -Method Simple | Format-Table

Write-Host "`nComprehensive Validation:"
Test-MultipleEmails -Emails $testEmails -Method Comprehensive | Format-Table

Write-Host "`nValidation with Domain Check:"
Test-MultipleEmails -Emails $testEmails -Method WithDomain | Format-Table

$sampleText = "Contact us at support@example.com or sales@company.co.uk for more information."
Write-Host "`nExtracting emails from text:"
Get-EmailsFromText -Text $sampleText

This toolkit includes the following functions:

  1. Test-EmailSimple: Uses a simple regex pattern to validate email addresses.
  2. Test-EmailComprehensive: Uses a more comprehensive regex pattern for stricter validation.
  3. Test-EmailWithDomain: Validates the email format and checks if the domain exists.
  4. Test-MultipleEmails: Validates multiple email addresses using one of the above methods.
  5. Get-EmailsFromText: Extracts email addresses from a given text.

To use this toolkit, you can copy and paste the entire script into a PowerShell file (e.g., EmailValidationToolkit.ps1) and then dot-source it in your PowerShell session:

. .\EmailValidationToolkit.ps1

PowerShell Toolkit for Regex IP Networking

# PowerShell Toolkit for Regex IP Networking

# Function to validate an IPv4 address
function Test-IPv4Address {
    param (
        [Parameter(Mandatory=$true)]
        [string]$IPAddress
    )
    
    $regex = '^\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b$'
    return $IPAddress -match $regex
}

# Function to validate an IPv6 address
function Test-IPv6Address {
    param (
        [Parameter(Mandatory=$true)]
        [string]$IPAddress
    )
    
    $regex = '^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$'
    return $IPAddress -match $regex
}

# Function to extract all IPv4 addresses from a string
function Get-IPv4Addresses {
    param (
        [Parameter(Mandatory=$true)]
        [string]$InputString
    )
    
    $regex = '\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
    return $InputString | Select-String -Pattern $regex -AllMatches | ForEach-Object { $_.Matches.Value }
}

# Function to extract all IPv6 addresses from a string
function Get-IPv6Addresses {
    param (
        [Parameter(Mandatory=$true)]
        [string]$InputString
    )
    
    $regex = '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))'
    return $InputString | Select-String -Pattern $regex -AllMatches | ForEach-Object { $_.Matches.Value }
}

# Function to validate a subnet mask
function Test-SubnetMask {
    param (
        [Parameter(Mandatory=$true)]
        [string]$SubnetMask
    )
    
    $regex = '^(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))$'
    return $SubnetMask -match $regex
}

# Function to validate CIDR notation
function Test-CIDRNotation {
    param (
        [Parameter(Mandatory=$true)]
        [string]$CIDR
    )
    
    $regex = '^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))$'
    return $CIDR -match $regex
}

# Function to extract network address from CIDR notation
function Get-NetworkAddress {
    param (
        [Parameter(Mandatory=$true)]
        [string]$CIDR
    )
    
    if (Test-CIDRNotation $CIDR) {
        $parts = $CIDR -split '/'
        $ip = $parts[0]
        $mask = [int]$parts[1]
        
        $ipBytes = [System.Net.IPAddress]::Parse($ip).GetAddressBytes()
        $maskBytes = [byte[]](,0xFF * 4)
        for ($i = 0; $i -lt 4; $i++) {
            if ($mask -lt 8) {
                $maskBytes[$i] = [byte]((0xFF -shl (8 - $mask)) -band 0xFF)
                $mask = 0
            } else {
                $mask -= 8
            }
        }
        
        $networkBytes = for ($i = 0; $i -lt 4; $i++) {
            $ipBytes[$i] -band $maskBytes[$i]
        }
        
        return [System.Net.IPAddress]($networkBytes)
    } else {
        Write-Error "Invalid CIDR notation"
        return $null
    }
}

# Example usage:
# Test-IPv4Address "192.168.1.1"
# Test-IPv6Address "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
# Get-IPv4Addresses "The IP addresses are 192.168.1.1 and 10.0.0.1"
# Get-IPv6Addresses "IPv6 addresses: 2001:0db8:85a3::8a2e:0370:7334 and fe80::1"
# Test-SubnetMask "255.255.255.0"
# Test-CIDRNotation "192.168.1.0/24"
# Get-NetworkAddress "192.168.1.100/24"

This toolkit provides the following functions:

  1. Test-IPv4Address: Validates an IPv4 address.
  2. Test-IPv6Address: Validates an IPv6 address.
  3. Get-IPv4Addresses: Extracts all IPv4 addresses from a given string.
  4. Get-IPv6Addresses: Extracts all IPv6 addresses from a given string.
  5. Test-SubnetMask: Validates a subnet mask.
  6. Test-CIDRNotation: Validates CIDR notation.
  7. Get-NetworkAddress: Extracts the network address from CIDR notation.

You can use these functions in your PowerShell scripts or directly in the PowerShell console. The example usage at the end of the script shows how to call each function.

Regular Expression (regex) in PowerShell

ElementDescriptionExample
.Matches any single character except newline“h.t” matches “hat”, “hot”, “hit”
*Matches zero or more occurrences of the previous character“a*b” matches “b”, “ab”, “aab”, “aaab”
+Matches one or more occurrences of the previous character“a+b” matches “ab”, “aab”, “aaab”, but not “b”
?Matches zero or one occurrence of the previous character“colou?r” matches “color” and “colour”
^Matches the start of a line“^Hello” matches “Hello World” but not “World Hello”
$Matches the end of a line“World$” matches “Hello World” but not “World Hello”
[ ]Matches any single character in brackets“[aeiou]” matches any vowel
[^ ]Matches any single character not in brackets“[^aeiou]” matches any consonant
( )Groups characters“(ab)+” matches “ab”, “abab”, “ababab”
|Alternation (OR)“cat|dog” matches “cat” or “dog”
{ }Specifies exact number of occurrences to match“a{3}” matches exactly three “a”s
\dMatches any digit“\d{3}” matches three digits
\DMatches any non-digit“\D+” matches one or more non-digits
\wMatches any word character (a-z, A-Z, 0-9, _)“\w+” matches one or more word characters
\WMatches any non-word character“\W” matches any single non-word character
\sMatches any whitespace character“\s” matches space, tab, newline
\SMatches any non-whitespace character“\S+” matches one or more non-whitespace characters
\bMatches a word boundary“\bword\b” matches “word” as a whole word
\BMatches a non-word boundary“\Bword\B” matches “word” only if it’s part of a larger word
(?i)Makes the match case-insensitive“(?i)hello” matches “hello”, “Hello”, “HELLO”
(?m)Enables multiline mode“(?m)^start” matches “start” at the beginning of any line
(?s)Enables single-line mode (dot matches newline)“(?s).*” matches everything including newlines
(?<name>…)Named capturing group“(?<year>\d{4})” captures a year in a named group
(?:…)Non-capturing group“(?:ab)+” matches “ab”, “abab” without creating a capture group
(?=…)Positive lookahead“Jacob(?=\sSm)” matches “Jacob” only if followed by ” Sm”
(?!…)Negative lookahead“Jacob(?!\sSm)” matches “Jacob” only if not followed by ” Sm”
(?<=…)Positive lookbehind“(?<=Mr.)\s\w+” matches a name if preceded by “Mr.”
(?<!…)Negative lookbehind“(?<!Mr.)\s\w+” matches a name if not preceded by “Mr.”