Enabling AD account using powershell - powershell

All the new user accounts created in Active Directory are kept as disabled and the option "user must change password on next login" is ticked. This accounts will remain as disabled for 7 days and in the 8th day it needs to be enabled.. Creating the account is already done by another script and I am stuck with account enable part.
How can I archive enabling these account using PowerShell script? How to use all account properties like lastlogon date, account creation date, account status(disabled), and the option "user must change password on next login" to validate and find the user is a new user which needs to enable?
get-aduser -f {-not ( lastlogontimestamp -like "*") -and (enabled -eq $false) -and (pwdLastSet -eq 0)} |
Select-Object name,SamAccountName |
export-csv -path data.csv

Use filters to filter according to your criteria. This snippet gets user objects for accounts that are disabled then filters out those less than a week old. It stores them in a collection of user objects. You can further filter $userlist by any user object property using the $variable | $variable where { [filter] } format. The filters can be as complex as you want. I like putting one on each line so I can easily comment out given filters. Use the filtered list for whatever you want.
$WeekAgoDate = $(Get-Date).addDays(-7)
$userlist = get-aduser -filter { enabled -eq $false } -Properties *
$userlist = $userlist | Where { $_.created -lt $WeekAgoDate }
"$userlist.count accounts found"
$userlist | select name, samaccountname | format-table
To enable $userlist:
$userlist | Enable-ADAccount

Here is how you can do it but you will need to write the script:
Check the whenCreated attribute It has a date time stamp and you can use that to see how old the account is.
If the account is older then 7 days and the account is disabled set the userAccountControl attribute to enabled IE 512 and then set your user must change password property true

Related

Find all active AD users in specified period

I need some help with finding all active AD Users. The task is to find all users, that had been active for 8 months. So far, I managed to find all users that are active right now, but I need the specific period. Here's my Powershell code:
PS C:\Windows\system32> Get-ADUser -Filter 'enabled -eq $true' -Properties CN |
Select-Object #{Label='ParentContainer';Expression={$_.Distinguishedname -replace "CN=$($_.cn),"}} |
Group-Object -Property ParentContainer |
Select-Object Name,Count
| Out-File -FilePath C:\Users2.txt
Thx in advance
it seems that you need to know when the user has been disabled to find its history and find out the active users within a period
for example, if the users disable before last month that means it was active last month
this link will show that
https://social.technet.microsoft.com/Forums/en-US/2560e797-a929-4fe0-bfcb-8e7d850d865b/ad-users-disabled-date

Get samaccountname from display name - but with extras

First time poster but site has helped me so much in the past.
We are an MSP and regularly get requests from clients to pull various details off a list of users they send us. Unfortunately though their lists rarely (if ever) contain any unique identifiers for AD such as samAccountName or even e-mail.
So typically I only get their first and last names, job titles etc. and use a slight variation on the below to try and get the required samAccountNames to work in batch modify scripts.
Get Samaccountname from display name into .csv
The problem comes (and caused a big headache recently) when I try to put that output back into a table to line up with the displaynames. As if the script can't find the displayname it just moves onto the next one in the list and puts the samAccountName directly below the last one it found. making it out of line with the displayname column I've put it beside.
My question is is there something I can add to the below script that when an error occurs it simply inputs null or similar into the samAccountName output csv so I could spot that easily in an excel sheet.
Similarly some users have multiple accounts like an admin and non-admin account with the same display name but different samAccountName so it pulls both of them, which is less of a problem but also if there was any way to have the script let me know when that happens? That would be super useful for future.
Import-Module activedirectory
$displayname = #()
$names = get-content "c:\temp\users.csv"
foreach ($name in $names) {
$displaynamedetails = Get-ADUser -filter { DisplayName -eq $name } -server "domain.local"| Select name,samAccountName
$displayname += $displaynamedetails
}
$displayname | Export-Csv "C:\temp\Samaccountname.csv"
So the problem lies in that you rely on Get-ADUser to provide you with user objects and when it doesn't you have gaps in your output. You instead need to create an object for every name/line in your "csv" regardless of whether Get-ADUser finds anything.
Get-Content 'c:\temp\users.csv' |
ForEach-Object {
$name = $_
$adUser = Get-ADUser -Filter "DisplayName -eq '$name'" -Server 'domain.local'
# Create object for every user in users.csv even if Get-ADUser returns nothing
[PSCustomObject]#{
DisplayName = $name # this will be populated with name from the csv file
SamAccountName = $adUser.SamAccountName # this will be empty if $adUser is empty
}
} | Export-Csv 'C:\temp\Samaccountname.csv'

AD GUI shows properties that PowerShell returns empty

I want to get a list of all AD Users and their creation time and last logon time. First I used the Active Diretory Users and Computers app and activated the Advanced Features. In the Attribute Editor I can see the properties are called LastLogon and WhenCreated.
So I did this:
$allUsers = Get-ADUser -Filter * -Properties SamAccountName,LastLogon,WhenCreated
$allUsers | select SamAccountName,LastLogon,WhenCreated
However LastLogonand WhenCreated are only filled for 13 of 500 Users. In the Attribute Editor these values are filled for a lot more...
When I query one user only that has these values in the Attribute Editor with Get-ADUser -Identity $User -Properties * I see that the attributes are called LastLogonDateand Created (values are shown empty).
So I searched for those attributes:
$allUsers2= Get-ADUser -Filter * -Properties SamAccountName,LastLogonDate,Created
$allUsers2 | select SamAccountName,LastLogonDate,Created
Then again those 13 have the info the rest doesn't.
Has anyone an idea how I get those values? (I am going to export them with Export-CSV so another way to get those in Excel is ok, too )
As requested my comments as answer.
First attempt:
Add the -Server switch on Get-ADUser and have it query the same Domain Controller you are currently connected to with Active Directory Users and Computers. It may be that you are asking for properties that have not yet been synchronized (especially the lastLogon time stamp which I believe is synced only once every 14 days unless you have specified a different value for the ms-DS-Logon-Time-Sync-Interval attribute on the domain default naming context.)
--> didn't apply because you're running this on the DC itself
Second attempt:
Try ADSI as in $searcher = [adsisearcher]'(&(objectCategory=person)(objectClass=user))'; $searcher.FindAll()
--> same results as with Get-ADUser; still empty values
Third attempt:
Check PowerShell version(s)
--> apparently the DC had PS version 4. With version 5.1 it works
First, look at what properties your cmdlet has:
$a = Get-ADUser -server 'DomenNameTest.en' -Identity 'makarovayu' -Properties *
$a | Get-Member
I recommend copying the received data into a notepad in order to copy the available field names later.
2-Let's declare an array and use the cmdlet to try to collect information on the required fields
$userList = Get-ADUser -server 'DomenNameTest.en' -Properties SamAccountName,Name -Filter * |
#Do not forget that the comanlet has a limitation and can fall off on timeout.See how I work with each property in [select]
Select #{Name = "SamAccountName"; Expression={$_.SamAccountName}},#{Name = "Name"; Expression={$_.Name}} |
#Uploading data to [csv]
Export-Csv -Path "D:\Users\userTest\Desktop\userList.csv" -Append -NoTypeInformation -Encoding Default -Delimiter ';'
Remove-Variable a,userList #Clear the variables

How to find AD users where no password is set?

How can I find AD-users where the password has not been set?
Some backgrund information:
We have a script (written in C#) that creates AD users and sets a default password. The user is prompted to change this password at the first attempt to login.
The script runs fine but recently we discoverd that the password was not set in a few cases. And it keeps happening now and then. We are investigating this issue at the moment.
Now I wan't to find the users where the default password hasn't been set by the script in order to set the default password manually where required.
When I look at the AD attributes of a user I can't see an obvious way to find these users without (default) password set.
The pwdLastSet is 0x0 when the user is created form the script and the password has been set with succes (tested). So how to know when the password hasn't been set?
What you are after is Get-ADReplicationAttributeMetadata.
Give this one a go, you should be able to set it to what you need. It is fairly fast so you can add results to a hashtable and pump that out when done.
I have this pumped into a nice little function with $Username and $ServerName as params.
The main attributes you are after are pwdLastSet, ntPwdHistory and lastLogonTimestamp.
Get-ADuser $username |
Get-ADReplicationAttributeMetadata -Server $ServerName |
Where-Object Version -GT 1 | Select AttributeName, LastOriginatingChangeTime, Version | OGV
The version will tell you how many times it has been changed while the LastOriginatingChangeTime will tell you when. If you do a Select * and remove the Where-Object Version -GT 1 you can see the other data it pulls.
EDIT:
Looks like Get-ADReplicationAttributeMetadata is not available on version 2.
PSVersion Get-ADReplicationAttributeMetadata
--------- ----------------------------------
2 False
3 True
4 True
5 True
The PasswordLastSet attribut could do it. It saves the date when the password was set the last time.
Get-ADUser -Filter * -Properties PasswordLastSet | Where-Object { $_.PasswordLastSet -eq $null }
It IS possible to have users in AD that have a blank password, despite activated password policy. This is due to the PASSWD_NOTREQD flag in the userAccountControl property of a user. The value for this PASSWD_NOTREQD flag is 32.
To check for enabled users that have this flag (and therefore don't need a password) you can do
$noPwdRequired = Get-ADUser -LDAPFilter "(&(objectClass=user)(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=544))"
foreach($user in $noPwdRequired ){
Write-Host $user.sAMAccountName # or displayName or whatever you want to identify the user
}
Normally, a user object has the default value of 512 (NORMAL_ACCOUNT). With the PASSWD_NOTREQD they will have a value of 544
Use value 546 to find disabled accounts that also has this flag set.
You can update this for any of those found users doing something like
$noPwdRequired = Get-ADUser -LDAPFilter "(&(objectClass=user)(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=544))"
foreach($user in $noPwdRequired ){
Set-ADAccountControl $user -PasswordNotRequired $false
}

Using PowerShell how can I search and filter an array of exported Active Directory users like I can with Get-ADUser?

I have a PowerShell script that compares the contents of a CSV file with Active Directory. The CSV file contains a list of demographic information of people already in AD. One of the columns is "emplid". The values in this field correspond to the values of the "employeeID" attribute of user objects in AD. So, I currently use this "emplid" property to cross reference AD and find the corresponding user accounts. To do this I use a line similar to this:
$UserAccounts = $ListOfEmloyeeIDs | ForEach-Object {Get-ADUser -Properties * -Filter {employeeID -Eq $_}}
I then use this to add those user accounts to a security group:
$UserAccounts.SamAccountName | ForEach-Object {Add-ADGroupMember -Identity SpecialSecurityGroup -Members $_}
The problem is with the first line. There are thousands of user accounts and the script can take hours to run. This has also led to complaints from the AD admins. What I would like to do is load all active AD users into a variable (which takes less than 2 minutes to run) using:
$ADPeopleActive = Get-ADUser -SearchBase "OU=People,DC=MyAD,DC=com" -Properties EmployeeID -Filter {Enabled -Eq $True}
Then I would like to do my cross reference against this array and build a list of SamAccountNames to feed to something like my second line to populate my security group.
My problem is I can't figure out a way to do this cross reference against an array that I've built the same way I can cross reference with AD using Get-ADuser. Can anyone help?
Something like
$UserAccounts = $ADPeopleActive| Where-Object { $ListOfEmloyeeIDs -contains $_.EmployeeID }
?