stringpowershellreplacedistinguishedname

-replace (value) with an escape char?


I need to pull first and last names from accounts that were very poorly named from the previous IT administrator and recreate them in the same source OU. There are characters in the account name I that I cant seem to get past. I need to pull First,Last and the remaining DN so I can recreate the account in the same OU structure without. For testing I'm only using one user in one OU, but there will be many different OU structures. "\" and "(Vendor)" are causing

My end goal is to feed the script a list of Accounts DN and recreate the account without the undesired "\" and "(vendor)" and do first.last or some variation of that.

$source = "CN=last\, first (Vendor),OU=vendors,DC=somecompany,DC=com"
$arg = "(vendor)"
($source -split ',*..=')[1].Remove($arg)

I've also tried

($source -split ',*..=')[1] -replace "`(Vendor)'", ""

The brackets and \ seem to cause everything I've tried to fail. I've searched and there doesnt seem to be a simple escape char like ^ for Batch files.


Solution

  • The backtick is the escape character usually for just powershell code. In the regex though, you will want to double your backslashes.

    $source = "CN=last\, first (Vendor),OU=vendors,DC=somecompany,DC=com","CN=last\, first (Vendor),OU=vendors,DC=somecompany,DC=com"
    $r = ($source[0] -split ',*..=|\\,').Replace("(Vendor)","").Where({ $_ -ne ''})
    $r 
    

    For .remove() the argument is supposed to be a number, the number or characters to display of a string (and removing every character after the number of characters you give specify). Feeding it a string when it's expecting an int will just error so I used .replace() instead.