首页 > 解决方案 > 检查用户名列表,如果它们已经存在 Powershell

问题描述

我有一个包含 100 个用户名的 CSV,我现在必须检查它们是否已经存在。最好的方法是什么?如果用户名“marmar”已经被使用,程序是否有可能自行检查用户名“marmar1”或者是否同时使用“marmar2”是免费的?

通过 csv 读取用户名更容易还是应该将它们复制到 Powershell 中?用户名示例:

marmar langas ianmow lowbob berret lawpaw1

等等

开放的想法和提示。$

非常感谢

标签: powershellcsvactive-directory

解决方案


如果您的 CSV 文件看起来像

"UserName","OtherStuff"
"marmar","blah"
"langas2","blahblah"
"ianmow","blahblahblah"
"lowbob","blahblahblahblah"
"berret","blahblahblahblahblah"
"lawpaw1","blahblahblahblahblahblah"

你可以这样做:

$freeUserNames = Import-csv 'D:\UsersNamesToCheck.csv' | ForEach-Object {
    #Check to see if the user already exists in AD
    $name  = $_.UserName
    $dupes = Get-ADUser -Filter "SamAccountName -like '$name*'" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty SamAccountName
    $index = 1
    # check if the username is already in use and if so, increase the index number and test again
    while ($dupes -contains $name) {
        $name = '{0}{1}' -f ($name -replace '\d+$'), $index++
    }
    $name
}

# output on screen
Write-Host "Unused usernames:`r`n"
$freeUserNames

可能的输出:

Unused usernames:

marmar
langas1
ianmow1
lowbob
berret1
lawpaw2

推荐阅读