我需要一些技巧来替换文本文件中的名字,只用名字的第一个字母替换PowerShell(或其他东西)。拥有以下格式的文件:
givenName: John
displayName: John Forth
sAMAccountName: john.forth
mail: j.forth@mydomain.com
givenName: Peter
displayName: Peter Doe
sAMAccountName: peter.doe
mail: p.doe@mydomain.com
.......................
etc.
我在我的脚本中使用了powershell -replace并将@ somedomain.com替换为@ mydomain.com整个文件和其他一些字符串。它工作得很完美,但现在我需要将 sAMAccountName:john.forth 替换为 sAMAccountName:j.forth ,用于文件中的大约90个用户。有没有办法用脚本执行此操作或必须手动执行此操作?非常感谢你!
答案 0 :(得分:1)
您可以再次使用替换但使用不同的正则表达式。
这样的事情可能会发生
$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)
答案 1 :(得分:0)
这里有一个如何获取新值的示例,因为我猜你已经获得了在当前域名更改器中设置它的代码。
这两个的新值将是j.forth和p.doe,并且基于旧的SamAccountName。
$file = "givenName: John
displayName: John Forth
sAMAccountName: john.forth
mail: j.forth@mydomain.com
givenName: Peter
displayName: Peter Doe
sAMAccountName: peter.doe
mail: p.doe@mydomain.com"
$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
}
}