Patrick Rennings
Patrick Rennings

Reputation: 337

Powershell exist local user ADSI

I got the following code (working):

   #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"
}

But how is possible to build an check if the user already exists? I can not really find anything on the web :x

Upvotes: 2

Views: 8762

Answers (3)

mhu
mhu

Reputation: 18051

You can use the static Exists function of ADSI to check if an user exists:

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

But take note of this: [ADSI]::Exists throws an exception instead of returning False

Upvotes: 0

burton
burton

Reputation: 591

unfortunately, the ADSI interface seems to be broken in Windows 8.1. here's my workaround:

if (& net users | select-string "UserName") {
    #  user exists
} else {
    #  user not found
}

Upvotes: 0

CB.
CB.

Reputation: 60928

You can try this:

   #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"
    }
}

Upvotes: 2

Related Questions