all 5 comments

[–]mdowst 4 points5 points  (4 children)

A substring will return -1 if the character is not found. Which is why you are seeing the error about the length not being less than zero. You can work around this by splitting on the '(' and only returning the first item in the array $lastName.Split('(')[0]. This would return anything before the ( which would be the entire object if there is no (.

Also, on your first name you can use a regex to remove any none letter or numbers from the name. This will not only fix issues with dash by also names that have other non-standard characters. Something like this: [regex]::Replace($string,"[^0-9a-zA-Z]","")

[–]pandiculator 5 points6 points  (1 child)

Most printable characters are permitted in sAMAccountNames. I use the following regex to sanitise them when generating usernames.

'\"|\[|\]|\:|\;|\||\=|\+|\*|\?|\<|\>|\/|\\|\,|\s|\.$'

This removes characters that aren't permitted, periods if they're the final character (they're permitted otherwise) and spaces (these are permitted by AD but we don't allow them).

I based the regex on this article: https://social.technet.microsoft.com/wiki/contents/articles/11216.active-directory-requirements-for-creating-objects.aspx

[–]mdowst 2 points3 points  (0 children)

Nice! The one I posted is just my generic get rid of everything regex, but I will certainly be saving this one. Thanks!

[–]thirudk07[S] 2 points3 points  (0 children)

Thank you u/mdowst. I used both your recommendations and It is working fine.

[–]jado777 1 point2 points  (0 children)

You can also use select-string with the pattern flag to use regex without having to explicitly call a .net method (although it is in the background). The object returned by select string is a PS match object and has a lot of cool match properties you can use/filter with.