How to get more data from Get-ADuser with powershell - powershell

Import-Module ActiveDirectory
Get-ADUser -SearchBase "OU=CompanySite,DC=example,DC=domain,DC=com" -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties "SamAccountName","msDS-UserPasswordExpiryTimeComputed", "Department", "Title", "Manager" |
Select-Object -Property "SamAccountName", #{Name="Password Expiry Date"; Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}; #{Label="Manager";Expression={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}};# |
Export-Csv "C:\Update\PasswordExpired.csv" -NoTypeInformation
I am trying to get an CSV that contains the employees whose password is expiring and get their managers name, the employees job title, the employees name and the date the password will expire.
However when I run this, I am getting the employees name and date the password is expiring. No other fields. I dont understand where I went wrong

Ok, there were a few errors causing issues:
You had a semi-colon (;) after the Password Expiry Date property in the Select-object portion. This caused the code to terminate at that point. It should be a comma.
For the Manager property, your expression is incorrect. You have your end parentheses after SamAccountName. It should be before the period. Additionally you are trying to match the DN with the SamAccountName data so it will return nothing. Just do a Get-ADUser and set the identity as the $_.Manager output. From there you can use the parentheses to output whatever metadata you want from the full ADUser Object for the manager. You can swap out SamAccountName to DisplayName or something else.
Your code: (Get-ADUser -filter {SamAccountName-eq $_.Manager}.SamAccountName)
Correct code: (Get-ADUser $_.Manager).SamAccountName
Title and Name are not included because you aren't calling them in the Select-object code. The "-Properties" section of Get-ADUser only adds the attribute to the list of retrieved attributes. What you set in Select is what is output to the screen or file.
You had a comment (#) tag before the Export-CSV section so that wasn't running either.
Here's the code. I don't have the manager attribute in my AD so I wasn't able to validate that section, but the rest ran correctly. I've also made it a bit more transportable. The SearchBase is now specified in a variable, as is the export location for the file. Additionally, you don't need to specify SamAccountName in the -Properties section as this is a default attribute for Get-ADUser.
Import-Module ActiveDirectory
$SearchPath = "OU=CompanySite,DC=example,DC=domain,DC=com"
$ExportPath = 'C:\Update\PasswordExpired.csv'
$Users = Get-ADUser -SearchBase $SearchPath -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties "msDS-UserPasswordExpiryTimeComputed", "Department", "Title", "Manager"
$Users | Select-Object -Property Name,"SamAccountName",Title,#{Name="Password Expiry Date"; Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},#{Label="Manager";Expression={(Get-ADUser $_.Manager).sAMaccountName}} | Export-Csv $ExportPath -NoTypeInformation

Related

Searching for specific users created less than 30 days

I am trying to create a line of code that will search for a specific user (from a list). My current code below is not working as it doesn't bring back anything when you run it. However, if I remove the whenCreated field it finds something. The user I am testing this with was created yesterday so not sure why it is not being returned. Any help always appreciated.
$startDate = (Get-Date).Date
$endDate = $startDate.AddDays(-30).Date
Get-ADUser -filter {Surname -eq $e -and physicalDeliveryOfficeName -eq $site -and whencreated -ge $enddate} | Select-Object samAccountName -ExpandProperty samAccountName
I would suggest to first get all users created on or after your $enddate and who'se Office property is equal to your variable $site and then eventualy filter those that can be found in your array if last names.
Also, -Filter should be a string, not a scriptblock.
Try
Get-ADUser -Filter "Office -eq '$site' -and Created -ge $enddate" -Properties Office, Created |
Where-Object { $yourListOfLastNames -contains $_.Surname }
If need be, you can pipe through to a Select-Object to obtain only the properties you need for your output.
By default, Get-ADUser outputs objects with these properties:
DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
and in this case we've extended that to also have Office (= physicalDeliveryOfficeName) and Created (= whenCreated converted to DateTime)

Having some trouble filtering Get-ADUser using whenCreated powershell command

I can use some help structing/nesting the below powershell code to get the desired outcome.
When I use the command:
Get-ADGroupMember -Identity $groupname |
Get-ADUser -Properties * -Erroraction Ignore |
select #{N='UserName';E={$_.UserPrincipalName}} |
Export-csv $filename -NoTypeInformation
It works as expected and only selects people from the AD group $groupname, but when I modify the code and try to filter for only NEW accounts based on when the account was created, it's now including user accounts that are NOT in that group
Get-ADGroupMember -Identity $groupname |
Get-ADUser -Filter { whenCreated -ge $when } -Properties * -Erroraction Ignore |
select #{N = 'UserName'; E = { $_.UserPrincipalName } } |
Export-csv $filename -NoTypeInformation
I'm not sure why it is now including all new user accounts in our AD, even some outside of the group $groupname
You cannot use -Filter while piping in objects. If you are piping in objects Get-ADUser will assume you want to get them. This boils down to a parameter binding error, however, since you've set the -ErrorAction Ignore you aren't getting the error feedback that would have said so.
You should have any problem getting AD Users that we know exist by virtue of their group membership. So, I'd question if you really need to ignore errors. That said, Removing -ErrorAction Ignore will not solve the parameter binding issue. For that, I'm afraid you'll have to resort to post-filtering with a Where{} clause. For example:
$When = (Get-Date "12/31/2020").ToUniversalTime()
Get-ADGroupMember -Identity $groupname |
Get-ADUser -Properties WhenCreated |
Where-Object{ $_.WhenCreated -ge $when }
Select-Object #{Name = 'UserName'; Expression = { $_.UserPrincipalName } } |
Export-csv $filename -NoTypeInformation
Note: The property is stored in UTC, so by converting the local time we're interested in we should get the correct results.
Note: You do not need to get all the properties. UserPrincipalName is included in the default set. To post-filter you will have to add WhenCreated to the results.
An Aside: Try not to use script blocks for the -Filter argument. If you look at Get-ADUser help documentation you'll find the parameter is actually string typed. As such specifying a script block requires recasting under the hood and can lead to issues. so, if you were to use the -Filter parameter in this project or elsewhere just use a regular string, like: -Filter "Name -like '*steve*'"
Another Aside: A [DateTime] such as returned by Get-Date cannot be directly used in a -Filter argument. This likely has to do with If, when, and how cmdlet is manipulating the WhenCreated. The Value of the WhenCreated LDAP attribute is stored more like "20200820040000.Z", so you can adjust to use as the -Filter or -LDAPFilter argument respectively like below:
$when = (Get-Date '8/20/20' ).ToUniversaltime().ToString('yyyMMddHHmmss.Z')
Get-ADUser -Filter "WhenCreated -ge '$when'"
Or with -LDAPFilter
Get-ADUser -LDAPFilter "(whencreated>=$when)"
I'll follow-up with documentation on the filter-able properties if I can find it.
Update:
Based on comments from #SantiagoSquarzon, you may not want to use Get-ADGroupMember at all, as you may be passing non-user objects to Get-ADUser. Combining up his suggestion, an example may look like:
$when = (Get-Date '8/20/20' ).ToUniversaltime().ToString('yyyMMddHHmmss.Z')
$groupDN = (Get-ADGroup -Identity $groupname).DistinguishedName
Get-ADUser -LDAPFilter "(&(memberOf=$groupDN)(whencreated>=$when))" |
Select-Object #{Name = 'UserName'; Expression = { $_.UserPrincipalName }} |
Export-csv $filename -NoTypeInformation

Trying to input a specific user list for get-aduser

I'm trying to use a list of usernames to perform a simple get-aduser command. It works fine for a single user, but I can't input a file to perform this for a list.
This command works fine for a single user:
get-aduser -identity myusername -properties passwordlastset, passwordneverexpires |
sort name | ft Name, passwordlastset, Passwordneverexpires | out-file c:\PS\Output.txt
This works fine, but rather than use -filter * for all AD or identity pointing to a file, I am completely lost. I have tried doing a get-content and link to a file but I'm just getting into a pickle.
If I have a text file with a list of usernames in, how do I run the above command against that single text file list, rather than all of AD?
As a side query, is there a way that I can perform the above command, but for a specific OU?
If you have a list that isn't an object, either import it to an object or iterate over the values
Try something like:
$Userlist = Get-Content -path 'c:\temp\test.txt'
$Results = $Userlist | ForEach-Object {
Get-aduser -identity $_ -properties passwordlastset, passwordneverexpires
}
$Results | sort name | ft Name, passwordlastset, Passwordneverexpires | out-file c:\PS\Output.txt
This will work as long as you supply valid SamAccountNames in your list
I would do it this way. You can pipe in identity byvalue. You can import the csv later and get objects back.
get-content userlist.txt |
Get-aduser -properties passwordlastset, passwordneverexpires |
sort name |
select Name, passwordlastset, Passwordneverexpires |
export-csv users.csv
# searchbase example
get-aduser -filter 'name -like "j*"' -SearchBase 'OU=People,DC=stackoverflow,DC=com'

How to check user must change password at next logon flag via Powershell

I have been doing to report all user accounts that have the user must change password at next logon flag set, My question is : how do I set as user must change password at next logon instead of 1/1/1601 2:00:00 AM in CSV output ?
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed", "Title", "manager", "department", "employeeid" | Select-Object -Property "Displayname",#{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},"Title",#{n=”Manager Name”;e={(Get-ADuser -identity $_.Manager -properties displayname).DisplayName}},"Department","employeeid" | sort-object -property ExpiryDate | Export-Csv -Path "c:\export\expirydatenew.csv" -NoTypeInformation -Encoding UTF8
Calculated properties in select allow for real logic in their expressions, so you should be able to add
#{Name="User must change password";Expression={if($_.pwdLastSet -eq 0){"true"} else {"false"}}}
to your Select-Object
Also you need to add "pwdLastSet" to the properties you query with Get-ADUser
There is no logic issue!
Just as supplement... You can use either:
pwdLastSet with ($_.pwdLastSet -eq 0) or
PasswordLastSet attribute with a ($_.PasswordLastSet -eq $null) check.
Prior adding of either of two respectively to the queried properties with Get-ADUser is necessity.

How to get AD properties for a list of windows generic accounts?

I have below PowerShell commands, using which I can get the properties for all the users in the AD.
Import-Module ActiveDirectory
$attributes = 'SamAccountName', 'Name', 'Mail', 'PasswordLastSet', 'Enabled',
'PasswordNeverExpires', 'PasswordExpired'
Get-ADUser -Filter * -Properties $attributes | select $attributes
If I want properties for one specific user, I can use below example in a command prompt:
net user /domain testuser
But, how can I get the AD properties for given list of users?
So, far I have tried the below but couldnt achieve yet as it returns only for one user (not sure how to loop):
Import-Module ActiveDirectory
cd AD:
$Users = gc "C:\AD\accounts.txt"
Get-ADUser -Filter '*' -Properties DisplayName, Office |
? { $Users -contains $_.SamAccountName } |
select DisplayName, Office |
Export-Csv -Path "C:\AD\output\UserProp_14072016.csv" -NoTypeInformation
I'm looking for password last set, active or inactive, owner of that account.
Could you please help?
A technique I use for getting an arbitrary list of AD users is to construct an ORed LDAP filter from the text list:
$Users = gc "C:\AD\accounts.txt"
$User_filter = $Users -replace '^','(SamAccountName=' -replace '$',')'
$Filter = "(|$User_filter)"
Get-ADUser -LDAPFilter $Filter -Properties DisplayName,Office
You can try the following:
Import-Module ActiveDirectory
$Users = "Get-Content C:\AD\Accounts.txt"
Get-ADUser -Filter '*' -Properties DisplayName,Office,PasswordLastSet,LastLogonDate |
? {$Users -contains $_.SamAccountName} |
Select DisplayName,Office,PasswordLastSet,LastLogonDate |
Export-CSV -Path "C:\AD\output\UserProp_14072016.csv" -NoTypeInformation
I'm not aware of a specific "Active" property, but you can add the "LastLogonDate" to the Properties to determine when the account was last logged onto.
Additionally, I'm not sure what you're looking for when you are asking for the "Owner" of the account.
Incidentally, for a list of all of the properties available, you can do the following:
Get-ADUser <username> -Properties *
You may be able to find what you're looking for in the list.
Hope that helps.
Get last logon on descending order
Import-Module ActiveDirectory
Get-ADUser -filter * -properties Displayname, LastLogonDate, SamAccountName, office, PasswordLastSet | select-object Displayname, LastLogonDate,office, SamAccountName, PasswordExpired, PasswordLastSet | Sort LastLogonTime -Descending | Export-csv c:\users.csv -NoTypeInformation