我得到了以下代码(工作):
#Import File
$Users = Import-Csv C:\Users\Administrator\Desktop\userImport\users.csv
# Setting data
$compname = hostname
$computer = [ADSI]"WinNT://$compname"
$userGroup = [ADSI]"WinNT://./Users,Group"
# Loop to add all users
$Users | % {
# Create user itself
$createUser = $computer.Create("User",$_.userid)
# Set password (print1!)
$createUser.SetPassword($_.password)
$createUser.SetInfo()
# Create extra data
$createUser.Description = "Import via powershell"
$createUser.FullName = $_.'full name'
$createUser.SetInfo()
# Set standard flags (Password expire / Password change / Account disabled)
$createUser.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
$createUser.SetInfo()
# Adduser to standard user group ("SERVER02\Users")
$userGroup.Add($createUser.Path)
# Show that user X as been added
$username = $_.'full name'
echo "User $username added"
}
但是如果用户已经存在,如何构建检查? 我无法在网上找到任何东西:x
答案 0 :(得分:2)
你可以试试这个:
#Import File
$Users = Import-Csv C:\Users\Administrator\Desktop\userImport\users.csv
# Setting data
$compname = hostname
$computer = [ADSI]"WinNT://$compname"
$userGroup = [ADSI]"WinNT://./Users,Group"
$localUsers = $computer.Children | where {$_.SchemaClassName -eq 'user'} | % {$_.name[0].ToString()}
# Loop to add all users
$Users | % {
if($localUsers -NotContains $_.userID)
{
... do your job here....
}
else
{
write-host "User $($_.userID) already exists"
}
}
答案 1 :(得分:0)
不幸的是,ADSI界面似乎在Windows 8.1中被破坏了。这是我的解决方法:
if (& net users | select-string "UserName") {
# user exists
} else {
# user not found
}
答案 2 :(得分:0)
您可以使用ADSI的静态Exists
功能来检查用户是否存在:
[ADSI]::Exists('WinNT://./username')
但请注意:[ADSI]::Exists throws an exception instead of returning False