Filtering "DistinguishedName" Output with Search-ADAccount - powershell

I'm trying to search through AD using the Search-ADAccount cmdlet to find accounts which are Enabled but haven't logged in for the last 90 days. The below commands adequately finds enabled AD accounts on the domains which haven't logged in the last 90 days. However, I'm trying to filtering out any entries where the "DistinguishedName" field includes the text of "Service Account".
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 |
Select-Object -Property Name, Enabled, LastLogonDate, DistinguishedName |
Where-Object {
$_.Enabled -like 'True' -and
$_.DistinguishName -notmatch "Service Account"
}
The above command seems to work fine for finding the enabled accounts and last logon. However, whatever text I put in -notmatch "..." seems to be disregarded by PowerShell?
Also tried -notLike and I get the same behavior also.

Thanks boxdog for noticing the mis-spelling of the DisinguishedName in the Where-Object missing the "ed". This fixed the issue in combination with your other comment about the missing *Service Account* wildcards.
Updated PowerShell command:
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 |
Where-Object {
$_.Enabled -like 'True' -and
$_.DistinguishedName -NotLike "*Service Account*"
} |
Select-Object -Property Name,Enabled,LastLogonDate,DistinguishedName

Related

PS query to retrieve data from old environment via Powershell

I am running the below script with the intention to get all users that are currently enabled, password never expire, password last set and last logon date and it works just fine. I would like to add to the data the group those users/accounts belong to or any other information so i can contact their respective teams/managers to request clean up or decomm.
get-aduser -filter {Enabled -eq $TRUE} -properties passwordlastset, passwordneverexpires, lastlogonDate |
Select-Object Name, passwordlastset, Passwordneverexpires, lastlogonDate, DistinguishedName |
Export-Csv -Path 'C:\Temp\passlastset_enabledusers.csv'
How would i add this to this query. As it is works great but thought to avoid manual labor :)
Any advise? Thank you.
I personally like adding all of my properties to an array beforehand. Helps when you want to expand onto it in the future. As for the members groups, you need to create you own expression or else when you export to a csv it'll just say [Microsoft.ActiveDirectory.Management.ADPropertyValueCollection]. Also added the users manager as one of the properties it selects.
$properties = #(
"passwordlastset",
"passwordneverexpires",
"lastlogonDate",
"memberof"
)
Get-ADUser -Filter {Enabled -eq $true -and PasswordNeverExpires -eq $true} -properties $properties |
Select-Object Name, passwordlastset, Passwordneverexpires, lastlogonDate, DistinguishedName, Manager, #{Name='MemberOf';Expression={$_.MemberOf -join ';'}} |
Export-Csv -Path 'C:\Temp\passlastset_enabledusers.csv' -NoTypeInformation

active directory show locked users which are not expired

Is there a way to show the locked users, not disabled (if the password has typed wrong 3 time), which are are not expired (account not expired) either with AD query or a powershell script.
I searched on the net but couldn't find a solution.
This should work if your looking for locked out accounts which are not yet expired or without an expiration date set:
Search-ADAccount -LockedOut | where { $_.AccountExpirationDate -gt (Get-Date) -or $_.AccountExpirationDate -eq $null }
There is a way. You could import ActiveDirectory module and use Search-ADAccount cmdlet.
Search-ADAccount -LockedOut -UsersOnly | Where-Object { $_.PasswordExpired -eq $false }

How to retrieve only enabled users from the Active Directory

I'm trying to retrieve only enabled users in the AD. When I run this code line it returns the error. I tried using a filter as well to filter only enabled users for the requested info but it returns ALL users from every domain instead of just the single id.
Get-ADUser : A positional parameter cannot be found that accepts argument 'enabled -eq 'true''.
This is my code that is throwing the error.
Get-ADGroupMember -Identity 'Animal Shop A' | Get-ADUser -Filter '*' | Get-ADUser Where "enabled -eq 'true'" | Get-ADUser -Properties ('Mail')
This one returns ALL users from every domain
Get-ADGroupMember -Identity 'Animal Shop A' | Get-ADUser -Filter "enabled -eq'true'" | Get-ADUser -Properties ('Mail')
Is my syntax wrong on both of them? If I just want to return values from say "Animal shop A" and then "Animal Shop B"
.. or a little bit shorter this way:
Get-ADUser -Filter 'enabled -eq $true' -Properties mail |
Select-Object -Property Name,samaccountname,mail
Besides this I would recommend to use a -SearchBase. That's less stressful for the AD. ;-)
Get-ADUser -Filter * -Properties mail | Where { $_.Enabled -eq $True} | Select Name,samaccountname,mail
That will get all enabled users in your target domain that are enabled and display the name, username, and mail properties
Important to know for both commands:
You must work with an elevated powershell process.
Otherwise the result may not be complete.
get-aduser -filter 'enabled -eq "true"' -ResultSetSize $Null
simply try below commands in powershell as administrator permission.
As a guide, the first part will filter users, second part filtered enabled users and last part will give you export of results.
Get-ADUser -Filter * -Property Enabled | Where-Object {$_.Enabled -like “false”} | Export-Csv -Path C:\eport.csv -Encoding ascii -NoTypeInformation
hope to be useful for you.

Powershell command, to get users with expiring passwords in the next month or 30 days?

I'm having the hardest time getting the following output from powershell. The console just stops at the blinking cursor like the command is running, but I wait 20 min or so, and I still have no output, both in the powershell console, as well as when I try to export as a csv. I'm using the following command:
Search-ADAccount -AccountExpiring -DateTime "01/29/2017" | where {$_.ObjectClass -eq 'user'} | FT Name,ObjectClass -A | Export-Csv C:\temp
Could someone help? I've scoured the internet to no avail.
You are using format-table inappropriately. Don't use any Format-* cmdlets if you need to process the data after that point - formatting makes that impossible. Always save formatting for the very end, and only for user presentation.
Also, you're going to end up with a file in your C:\ root directory named temp that's not entirely usable as a CSV file, at least from Excel and other readers, because additional information is going to be inserted by Export-CSV. This will be eliminated by the -notypeinformation switch.
Additionally, you can speed this up by specifying the -UsersOnly switch for Search-ADAccount and skipping the where-object loop - the pipeline is really useful, but constructs like this can slow it down. Filter your data as far to the left as possible, and if you can do it inside a cmdlet that offers a filter, do it there.
Corrected script which should work as you expect:
Search-ADAccount -AccountExpiring -DateTime "01/29/2017" -UsersOnly | select-object -Property Name,ObjectClass | Export-Csv C:\temp\expiring.csv -NoTypeInformation;
Forgive me if this isn't perfect code, but this script will get you accounts expiring within the next 7 days. You can change the $DaysAhead variable to alter the time frame.
$maxPwdAge=(Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days;
$daysAhead = 7;
$dateMin=(get-date).AddDays(-$maxPwdAge);
$dateMax=$DateMin.AddDays($daysAhead);
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0} –Properties * | where {($_.PasswordLastSet) -ge $dateMin} |where {($_.PasswordLastSet) -le $dateMax} | select CN,EmailAddress,passwordLastSet | Format-Table;

migrate from get-qaduser to get-aduser

I have setup my script to disable inactive user in my Win 2003 AD server using Quest's AD tool GET-QADUSER, and now I am going to migrate AD to Win 2008 R2. Since there is Active Directory module and Quest's tool is no longer free to download (is that?), I am going to migrate to GET-ADUSER.
I am converting from:
Foreach ($ou in $searchBase) {
#$inactUsr += #(Get-QADUser -SearchRoot $ou -Enabled -PasswordNeverExpires:$false -NotLoggedOnFor $inactiveDays -CreatedBefore $creationCutoff -SizeLimit $sizeLimit | Select-Object Name,SamAccountName,LastLogonTimeStamp,Description,passwordneverexpires,canonicalName | Sort-Object Name)
}
to:
$inactUsr += #(Get-ADUser -SearchRoot $ou -Filter 'enabled -eq $true -and PasswordNeverExpires -eq $False' -Properties Name,SamAccountName,LastLogonTimeStamp,Description,passwordneverexpires,canonicalName | Select Name,SamAccountName,#{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}},Description,passwordneverexpires,canonicalName | Sort Name)
I am almost there and leave only -NotLogonFor (which select user that not logon for certain days) and -CreatedBefore (which give a grace period for newly created ID). I want to select ID NotLogon for 30 days and DO NOT want ID created less than 30 days.
Appreciate if anyone can let me know whether there is a built-in properties or any manual method to achieve that.
Edited:
I have the CreatedBefore solved by:
$inactUsrdraft += #(Get-ADUser -SearchBase $ou -Filter 'enabled -eq $true -and PasswordNeverExpires -eq $False -and whenCreated -le $CreationCutOff' -Properties Name,SamAccountName,LastLogonTimeStamp,Description,passwordneverexpires,canonicalName | Select Name,SamAccountName,#{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}},Description,passwordneverexpires,canonicalName | Sort Name)
:)
Now I need only need to filter ID not logon more than 30 days.
Any help is appreciated.
How about:
$LastLogonCutoff = (Get-Date).Date.AddDays(-30)
That's midnight 30 days ago. If you want it to the second, use (Get-Date).AddDays(-30).
Followed by changing the -Filter to include:
`-and (LastLogonTimeStamp -lt $LastLogonCutoff)`
Also beware that the LastLogonTimeStamp property is not very accurate. Laptop logins off-network that use saved credentials won't trigger, I believe. If you don't have "Wait for network" enabled, clients might never actually update this value, IIRC.