I'm building a script that lists all Inactive computer accounts. I'd like to exclude a few systems from the results.
I've got a text-file containing all systems to be excluded (one systemname per line). All items are stored in an object with property name "name". So $excluded will contain:
name
----
system1
system2
To list all inactive systems I use the Search-ADAccount cmdlet:
$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true}
Of course I can loop all results 1 by 1, but is there a simple way to exclude the systems directly from the results? I've got a feeling it's possible with select-object or where-object, but I can't figure out how to compare against the results in an object.
You were basically correct in using this in your title: "where {_.Name not in $object}"
Syntax is a little different. Pipe it to the following
Where { !($_.Name -in $excluded) }
OR
Where { $_.Name -notin $excluded }
Both seem to give the same results in the console. Happy coding!
Note: Tested this on PSv2 and v3.
I ran across this when looking for an answer and figured I would update with these options for others that run into this.
Import the exclude file (as csv) and use the -notcontains operator:
$names = Import-csv exclude.txt | Foreach-Object {$_.Name}
$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $names -notcontains $_.Name}
I think you can use -notcontains (TechNet article) operator:
$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $excluded -notcontains $_.name }
Related
I have a powershell script that his output is showing me everything that was disabled for the past 14 days.
What i'm looking is to change that this script will run from a specific OU and not the whole DC.
I want him to show me only the disabled users for the past 14 days from a specific OU.
The script:
$date = (Get-Date).AddDays(-14)
$disabledUsers = Get-ADObject -Filter 'ObjectClass -eq "User" -and whenChanged -ge $sixMonthsAgo -and UserAccountControl -band 2'
$server = Get-ADDomainController
foreach ($disabledUser in $disabledUsers)
{
Get-ADReplicationAttributeMetadata $disabledUser -Server $server -Properties UserAccountControl |
Where-Object { $_.AttributeName -eq 'UserAccountControl' } | Select Object, LastOriginatingChangeTime |
Where-Object { $_.LastOriginatingChangeTime -gt $date }
}
You should be aware that your current script actually works only if an object has not been modified since it was disabled.
But as far as I know, it is the only way without logging specificly userAccountControl attribute modification (and this cannot still log 100% of cases since once disabled, an object can see his userAccountControl modified without enabling it).
Based on "user is never modified after he was disabled" :
Search-ADAccount -SearchBase "OU=myOU,DC=mydom,DC=adds" -AccountDisabled -UsersOnly | Get-ADUser -Properties whenChanged | Where whenChanged -gt (Get-Date).AddDays(-14)
Using the Filter will make it run quickly
$date = (Get-Date).AddDays(-14)
get-aduser -filter {Enabled -eq $false -and Modified -ge $date } -Properties Modified | select samaccountname,Modified
I have the following code:
Search-ADAccount -AccountExpiring -TimeSpan "90" -ResultPageSize:100 -ErrorAction SilentlyContinue |
where {$_.samaccountname.StartsWith("X") -or $_.samaccountname.StartsWith("Y")} |
Select-Object samaccountname,Name,AccountExpirationDate |
Export-Csv $PSScriptRoot\Results\AD_Expiration_Dates_Accounts_Next_90_days_$((Get-Date).ToString('dd_MM_yyyy')).csv -NoTypeInformation -Append
I keep getting the error mentioned in the title with or without the -ResultPageSize: option.
The interesting thing is that when I change the -TimeSpan value I get more or less values and the data seems therefore to be coherent but, it always ends with the same error nevertheless.
The thing is, I'm not sure I can trust these values; even when I remove the option -ErrorAction SilentlyContinue I don't get any other error or information.
Does anyone have any input on this?
In this instance, it'd be way better to use Get-ADUser with a proper filter for all the criteria you want, rather than returning a whole lot of results and then using a where clause on them.
Also consider using the -searchbase option to limit which OU you search (if all the target accounts are in a specific OU).
$now = get-date
$90days = (get-date).adddays(90)
get-aduser -filter '(AccountExpirationDate -gt $now) -and (AccountExpirationDate -le $90days) -and (samAccountName -like "X*" -or sAMAccountName -like "Y*" )' -properties AccountExpirationDate
| Select-Object samaccountname,Name,AccountExpirationDate
I am trying to get a list of accounts with passwords that are older than lets say 90 days but something is not working right and I am not sure why.
Get-ADUser -Filter 'Enabled -eq $True' -Properties PasswordLastSet,samaccountname,passwordlastset | Where-Object {$_.PasswordLastSet -gt ($_.PasswordLastSet).adddays(1)} | select Name,samaccountname,passwordlastset
This is what i got so far but if I run it as is it returns 0 results. I know there are passwords that are older than one day, mine is one of them. Any help is appreciated.
Per your realization in the comments you should compare the PasswordLastSet field to today's date less 90 days as follows:
Get-ADUser -Filter 'Enabled -eq $True' -Properties PasswordLastSet | Where-Object {$_.PasswordLastSet -lt (Get-Date).adddays(-90)} | select Name,SamAccountName,PasswordLastSet
Use -lt for older passwords, or -gt for newer passwords.
You can try this,if you wana export remove #
$DaysAgo=(Get-Date).AddDays(-90)
$params = #{
"filter" = 'Enabled -eq $true -and passwordlastset -lt $DaysAgo'
"Properties" = "Displayname",
"passwordlastset",
"samaccountname"
}
Get-ADUser #params |select displayname,samaccountname,passwordlastset #| export-csv C:\result.csv -nti
I am trying to query a list of users while excluding a specific OU. This is also using Quest's AD snap-in for Get-QADUser. I have this:
$ExcludedOU = "Service Accounts"
$inactiveUsers = Get-QADUser -SizeLimit 3 -SearchRoot $sourceOu -NotLoggedOnFor $InactiveFor -Enabled | Where-Object {$_.description -notlike $DescriptionPrefix -and #{n="ParentContainerDN";e={($_.ParentContainerDN -split ",*..=")[0]}} -notlike $ExcludedOU }
The goal is to exclude any users where the parent OU is "Service Accounts". ParentContainerDN looks like OU=Service Accounts,OU=Our Users,DC=DOMAINNAME,DC=ORG
This query does not error, but it does not exclude either. This is the part I may not have the syntax correct on?
#{n="ParentContainerDN";e={($_.ParentContainerDN -split ",*..=")[0]}} -notlike $ExcludedOU
I was partially wrong about the regex portion of your split. I am still correct in that the string supports regular expressions. That query will split on the CN=, OU= and DN=.
However you placed calculated property syntax into a where-object clause. It didn't error out since it is a valid hashtable and hashtables support like and notlike. Calculated properties are used for things like Format-Table and Select-Object which you can then reference those "new" properties later in other pipes.
$inactiveUsers = Get-QADUser -SizeLimit 3 -SearchRoot $sourceOu -NotLoggedOnFor $InactiveFor -Enabled |
Select-Obejct Name,SamAccountName,Description,#{n="ParentContainerDN";e={($_.ParentContainerDN -split ",*..=")[0]}} |
Where-Object {$_.description -notlike $DescriptionPrefix -and $_.ParentContainerDN -notlike $ExcludedOU }
The above syntax is what was also done in the code you linked to on Social Technet
I cannot make this return false for the life of me. This will evaluate to true which might be why your query was not working as expected. This is valid PowerShell just not correct to use.
#{n="ParentContainerDN";e={$_.WhatEver}} -notlike "string"
However like Kai Zhao mentioned in comments this is not really used effectively and you can get the same results without the calculated property.
$inactiveUsers = Get-QADUser -SizeLimit 3 -SearchRoot $sourceOu -NotLoggedOnFor $InactiveFor -Enabled |
Where-Object {$_.description -notlike $DescriptionPrefix -and ($_.ParentContainerDN -split ",*..=")[1] -notlike $ExcludedOU}
I am wondering if there is a way to filter this:
Search-ADAccount -AccountInactive -DateTime ((get-date).adddays(-90))
-Usersonly
By adding pipeline:
| where-object {($_.samAccountName -notlike "*_ua1") -and ($ _.memberOf -like "*UserAdminL1 *")}
It seems like it freezes and do nothing.
Maybe there is a correct way to do this ?
Search-ADAccount does not return group memberships. If you want to filter on that you could first pipe into Get-AdUser to get the memberOf property. You also are missing the Where-Object portion of your filter and the $ _.memberOf should be $_.memberOf. Compile errors would have been trying to correct that for you so you might just have a copy paste issue with your question.
Search-ADAccount -AccountInactive -DateTime ((get-date).adddays(-90)) -Usersonly |
Get-Aduser -Properties memberof |
Where-Object {($_.samAccountName -notlike "*_ua1") -and ($_.memberOf -like "*UserAdminL1 *")}