Join Us!

Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.
A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.

Login

Enter your Project Envision username.
Enter the password that accompanies your username.
Request new password

Email Validation in PowerShell

Email address validation is one of the most common validations used used by sysadmins and developers. There are many approaches we can use, some of us prefer to write their own function, some will choose using 3rd party library. I will show the method which is “built-in” the PowerShell, Email Validation using System.Net.Mail.MailAddress  class.

Below source code presents a simple function to perform simple email address check.

function ValidateEmail{
    param([string]$address)
    ($address -as [System.Net.Mail.MailAddress]).Address `
        -eq $address -and $address -ne $null
}

The function accepts one parameter called $address.
We start from casting provided string as System.Net.Mail.MailAddress object.

($address -as [System.Net.Mail.MailAddress])

Then we take Address property of MailAddress object, which returns email address

($address -as [System.Net.Mail.MailAddress]).Address

and we comapre if it is equal to submitted parameter and if it is not null

-eq $address $address -ne $null

The function returns either $True, if it is valid email address or $False if it is not a valid email. I have created small usage example of ValidateEmail.

Example Usage

function ValidateEmail{
    param([string]$address)
    ($address -as [System.Net.Mail.MailAddress]).Address `
	-eq $address -and $address -ne $null
}
$result = ValidateEmail("test@test.com")
Write-Host $result
$result = ValidateEmail("test@")
Write-Host $result
$result = ValidateEmail("powershell")
Write-Host $result
$result = ValidateEmail("")
Write-Host $result

Output

PS C:\Users\KrystianZieja> .\Documents\ProjectEnvision\tmp\ValidateEmail.ps1
True
False
False
False
Categories: