Wednesday, 21 August 2013

Don't expire passwords of AD users the ADSI way

How to set as never to expire the password of Active Directory users through PowerShell using the ADSI adapter:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
$users = Import-Csv c:\temp\users.csv

foreach ($user in $users) {
        try {
                $ldap= "LDAP://" + "CN=" + $user.DisplayName + ",OU=Test,dc=riolo,dc=co,dc=uk"
                $u= [ADSI]$ldap
                $u.Put("userAccountControl", $u.UserAccountControl.Value -bor 65536)
                $u.SetInfo()
            }
        catch [System.Object]
            {
                Write-Output "Could not update user $($user.DisplayName), $_"
            }
   }

And this is an example of users.csv:

DisplayName
Alessandro Riolo
Ale Riolo
Alex Riolo
Alejandro Riolo
Alexander Riolo
Iskandar Riolo
Iskender Riolo
Aleksander Riolo
Sandro Riolo
Sasha Riolo
Alasdair Riolo
Alister Riolo

Create AD users in PowerShell following the ADSI way

How to create Active Directory users in PowerShell using the ADSI adapter:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
$users = Import-Csv c:\input\users.csv

$ou = [ADSI]"LDAP://OU=Test,dc=riolo,dc=co,dc=uk"

foreach ($user in $users) {
        try {
                $user
                $cn= "CN=" + $user.DisplayName
                $u = $ou.Create("user", $cn)
                $u.Put("sAMAccountName", $user.UserLogonName)
                $u.Put("UserPrincipalName",$user.UserLogonName + "@riolo.co.uk")
                $u.Put("sn", $user.LastName)
                $u.Put("givenName", $user.FirstName)
                $u.Put("displayName", $user.DisplayName)
                $u.Put("description", $user.Description)
                $u.Put("title", $user.JobTitle)
                $u.Put("company", $user.Company)
                $u.Put("department", $user.Department)
                $u.Put("manager", "CN=" + $user.Manager + ",OU=Test,dc=riolo,dc=co,dc=uk")
                $u.SetInfo()
                $u.Put("userAccountControl", (65536 -bor $u.userAccountControl.Value))
                $u.SetPassword("************")
                $u.psbase.InvokeSet("AccountDisabled",$false)
                $u.IsAccountLocked = $false
                $u.SetInfo()
                $u
            }
        catch [System.Object]
            {
                Write-Output "Could not create user $($user.UserLogonName), $_"
            }
   }

Where most lines will be self explanatory, bar perhaps:

021
                $u.Put("userAccountControl", (65536 -bor $u.userAccountControl.Value))
  

For which please look [1], [2] and above all [3].

And this is an example of users.csv:

UserLogonName,FirstName,LastName,DisplayName,Description,JobTitle,Department,Company,Manager
Test_User_1,Test User 1,MyApp,Test User MyApp 1,Test User for MyApp 1,Test User,QA Team,Riolo inc.,QA Manager