When writing powershell scritps that need to deal with Active Directory you'll, eventually, have to work with distinguishedNames. Finding the domain or the OU in which the object is useful in most situation.
Here's a regular expression to use against an object distinguishedName that return a $Matches object containing:
- commonName of the object (CN=...)
- name of the object
- path of the object
- domain part of the path
^(?:(?<cn>CN=(?<name>[^,]*)),)?(?:(?<path>(?:(?:CN|OU)=[^,]+,?)+),)?(?<domain>(?:DC=[^,]+,?)+)$
You can test it on regexr.com at this url: https://regexr.com/3l4au
Cheers