Use PowerShell to extract an email address from a string

less than 1 minute read

March 2021

Short post on how to use PowerShell and regex to extract an email address from a string.

I was recently given a spreadsheet of Azure AD groups and users that should added to those groups. The users were in various formats but did include their email address per line (which matches their UPN in Azure AD).

I used the following script to extract the user’s email address to a list and then used the list to update the AzureAD group (I used Import-CSV Cmdlet to assign the $userList values - in the below example the strings are assigned directly for demonstration purposes).

How it works

  • A list of string types is created, initialised and assigned to the variable $emailList.
  • A foreach loop is used to iterate over the user details assigned to the $userList variable.
  • Each string is matched against the email regex pattern and if a portion of the string matches the regex, it is stored in the $Matches automatic variable value property.
  • This value is added to the $emailList.

Showing output of email addresses from script