Reputation: 11
I need some tips to replace first name in a text file with just first letter of the name with powershell (or something). Have file in this format:
givenName: John
displayName: John Forth
sAMAccountName: john.forth
mail: [email protected]
givenName: Peter
displayName: Peter Doe
sAMAccountName: peter.doe
mail: [email protected]
.......................
etc.
I used powershell -replace in my scripts and replace @somedomain.com to @mydomain.com whole file and some other strings. It works perfect, but now I need to replace sAMAccountName: john.forth with sAMAccountName: j.forth for about 90 users in file. Is there any way to do this with script or have to do it manually? Thank you a lot!
Upvotes: 0
Views: 1041
Reputation: 11
Here you have an example how you can get the new value, since I'm guessing you already got the code for setting it in your current domain changer.
The new values for these two will be j.forth and p.doe and are based of the old SamAccountName.
$file = "givenName: John
displayName: John Forth
sAMAccountName: john.forth
mail: [email protected]
givenName: Peter
displayName: Peter Doe
sAMAccountName: peter.doe
mail: [email protected]"
$file = $file -split "`n"
Foreach($line in $file){
# identifier to look for
$id = "sAMAccountName: "
# if identifier found in line
if($line -match $id){
# removing identifier to get to value
$value = $line -replace $id
# splitting on first dot
$givenname = $value.split(".")[0]
# new value
$newvalue = ($givenname.SubString(0,1))+($value -replace ($givenname))
$newvalue
}
}
Upvotes: 0
Reputation: 58441
You can use replace again but with a different regex.
Something like this might do
$result = $subject -replace '(?<=sAMAccountName: \w)\w+', ''
'(?<=' + # Assert that the regex below can be matched backwards at this position (positive lookbehind)
'sAMAccountName: ' + # Match the character string “sAMAccountName: ” literally (case sensitive)
'\w' + # Match a single character that is a “word character” (Unicode; any letter or ideograph, digit, connector punctuation)
')' +
'\w' + # Match a single character that is a “word character” (Unicode; any letter or ideograph, digit, connector punctuation)
'+' # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
Upvotes: 1