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"

# 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

4

3 回答 3

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"
    }
}
于 2012-12-03T14:48:52.963 回答
0

不幸的是,ADSI 接口似乎在 Windows 8.1 中被破坏了。这是我的解决方法:

if (& net users | select-string "UserName") {
    #  user exists
} else {
    #  user not found
}
于 2014-08-26T16:36:42.497 回答
0

您可以使用ExistsADSI 的静态函数来检查用户是否存在:

[ADSI]::Exists('WinNT://./username')

但请注意这一点:[ADSI]::Exists 抛出异常而不是返回 False

于 2016-03-31T12:27:33.823 回答