Reputation: 39
In PowerShell, I'm looking to convert a SharePoint Location string (john_smith_domain_com) to the proper addressing of [email protected].
I'm not sure which is the best way to go about doing this.
I know $var.Replace("_",".")
would work to replace all the "_"s with "."s, but that doesn't help the "@" going between the name and the domain.
Unfortunately, the domain isn't always the same, or I'd be able to just .replace it easily.
Upvotes: 2
Views: 369
Reputation: 437638
You can combine two -replace
operations (this assumes a two-component domain name, such as domain.com
):
# -> '[email protected]'
'john_smith_domain_com' -replace '_(?![^_]+_[^_]+$)', '.' -replace '_', '@'
Regex _(?![^_]+_[^_]+$)
matches all _
chars. except the second-to-last one.
After all these have been replaced with .
, only the second-to-last one is left, which can then be replaced with @
As JohnLBevan notes, if there are domain names with a varying number of components, you have two options:
<firstName>.<lastName>
(as governed by a policy), you can replace the second _
with @
:# -> '[email protected]'
'john_smith_domain_co_uk' -replace '^([^_]+)_([^_]+)_', '$1.$2@' -replace '_', '.'
You may want something that's aware of the more common TLDs / caters for more common domain formats. Some options are in this post.
Upvotes: 3