将名称替换为第一个字母powershell

问题描述 投票:0回答:2

我需要一些技巧来替换文本文件中的名字,只用名字的第一个字母和powershell(或其他东西)。拥有以下格式的文件:

givenName: John
displayName: John Forth
sAMAccountName: john.forth
mail: [email protected]

givenName: Peter
displayName: Peter Doe
sAMAccountName: peter.doe
mail: [email protected]

.......................
etc.

我在我的脚本中使用了powershell -replace并将@ somedomain.com替换为@ mydomain.com整个文件和其他一些字符串。它工作得很完美,但现在我需要用sAMAccountName:j.forth替换sAMAccountName:john.forth,用于文件中的大约90个用户。有没有办法用脚本执行此操作或必须手动执行此操作?非常感谢!

string powershell replace
2个回答
1
投票

您可以再次使用替换,但使用不同的正则表达式。

这样的事情可能会发生

$result = $subject -replace '(?<=sAMAccountName: \w)\w+', ''

Breakdown

'(?<=' +                   # 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)

0
投票

这里有一个如何获取新值的示例,因为我猜你已经获得了在当前域名更改器中设置它的代码。

这两个的新值将是j.forth和p.doe,并且基于旧的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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.