I am trying to get the user count and the actual userinformation through get-aduser but fail miserably.
Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' -and $_.samaccountname -notlike '*health*' } | Select-object Samaccountname,surname,givenname | Where { $excludedusers -NotContains$_.Samaccountname } | format-list > 'C:\Scripts\Test\enabled_users_and count.csv'
Is the current code. I can add a .count before format-list like this:
(Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' -and $_.samaccountname -notlike '*health*' } | Select-object Samaccountname,surname,givenname | Where { $excludedusers -NotContains$_.Samaccountname }).count
But I only get the count of the users, as earlier said, I need both.
Extremely thankful for the help.
You need Two different things, Count don't need to be a field in the csv, you can get it by the line count of the final output
You might need the count for the console use, anyway it's not logically right to save it in the final output. (if I understand you right)
You can save it to a variable, then do export or count check...
$Users = Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} |
Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' -and $_.samaccountname -notlike '*health*' } |
Where { $excludedusers -NotContains $_.Samaccountname }
Export:
$Users | Select-object Samaccountname,surname,givenname |
Export-CSV 'C:\Scripts\Test\enabled_users_and count.csv'
Check Count:
$Users.Count
Related
I posted 4 days ago and the community have been really helpful! I can now look for users in a specific parent OU who have a last name.
My second step that I am trying to do is to now add those users who have a last name and are in the parent OU to a mail enabled security group. After some googling I found a piece of script that allows users to be added to such, but I need to edit to to specify my requirements. I thought I had tried to do this but it ended up still searching through the child OUs and adding those without a last name so I must have something wrong or jumbled.
My current script is
$Admin_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Service_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Disabled = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Test_PowerPoint_GPO = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Exclude = '({0}|{1}|{2})$' -f \[regex\]::Escape($Admin_Accounts), \[regex\]::Escape($Service_Accounts), \[regex\]::Escape($Disabled), \[regex\]::Escape($Test_PowerPoint_GPO)
Get-ADUser -Filter 'Enabled -eq $true' -SearchBase 'OU=Users,OU=Company,DC=CompanyDC,DC=local' |
Where-Object { !\[string\]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude } |
Select-Object SamAccountName
$TargetGroup = “Company Team“
$TargetOU = “OU=Users,OU=Company,DC=Company,DC=local“
$Exclude = '({0}|{1}|{2})$' -f \[regex\]::Escape($Admin_Accounts), \[regex\]::Escape($Service_Accounts), \[regex\]::Escape($Disabled), \[regex\]::Escape($Test_PowerPoint_GPO)
$UserAccounts = Get-ADUser -Filter 'Enabled -eq $true' | ?{$_.DistinguishedName -like “_*$TargetOU*” -and $.Enabled -eq “True”}
Where-Object { !\[string\]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude } |
Select-Object SamAccountName
ForEach($User in $UserAccounts)
{
$UsersName = $User.Name
\#Check for group membership
$Membership = Get-ADGroup $TargetGroup | Get-ADGroupMember | ?{$\_.Name -eq $UsersName}
if(!$Membership)
{
“Adding $UsersName to $TargetGroup”
Get-ADGroup $TargetGroup | Add-ADGroupMember -Members $User -Verbose
}
}
I tried to add pieces of script to specify my requirements
Seems to me your script is way more complex than it needs to be:
$Admin_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Service_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Disabled = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Test_PowerPoint_GPO = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
# Create regex matching list
[regex]$Exclude = "$Admin_Accounts|$Service_Accounts|$Disabled|$Test_PowerPoint_GPO"
$UserAccounts = Get-ADUser -Filter 'Enabled -eq $true' | Where-Object {
$_.DistinguishedName -like “_*$TargetOU*”
} | Where-Object {
![string]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude
} | Select-Object SamAccountName
Im trying to write a script that goes through a CSV-File, searches up the Username in our AD and then gives me these users, that have a specific E-Maildomain and hasn't logged in for the last 90 days.
Here's what I got so far:
import-csv C:\pathtofile\user.csv | ForEach-Object {
Get-ADUser $_.SamAccountName -Filter "EMailAddress -like '*#thedomain.com'" -Properties SamAccountName,LastLogonDate | Where { ($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)} | Sort | Select Name,SamAccountName,LastLogonDate
}
But it gives me this weird error:
Get-ADUser : A positional parameter cannot be found that accepts argument 'Username'.
I tried to put the E-Mailsorting into my where-statement, but it was not able to find any users then...
Can you guys may see what I'm doing wrong?
Thank you for your help.
Kind regards,
Gabe
You cannot use parameter -Filter together with -Identity.
(using Get-ADUser $_.SamAccountName implicitely uses the -Identity parameter)
To filter out only users that are in your CSV file AND that have a specific domain in their email address, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Import-Csv -Path 'C:\pathtofile\user.csv' | ForEach-Object {
$userSam = $_.SamAccountName
try {
$user = Get-ADUser $userSam -Properties EmailAddress, LastLogonDate -ErrorAction Stop
if (($user.LastLogonDate) -and $user.LastLogonDate -lt $refDate -and
$user.EmailAddress -like '*#thedomain.com') {
$user | Select-Object Name,SamAccountName,EmailAddress,LastLogonDate
}
}
catch {
Write-Warning "User '$userSam' not found"
}
}
To filter out all users that have a specific domain in their email address, so not using the csv at all, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Get-ADUser -Filter "EmailAddress -like '*#thedomain.com'" -Properties EmailAddress, LastLogonDate |
Where-Object { ($_.LastLogonDate) -and $_.LastLogonDate -lt $refDate } |
Select-Object Name,SamAccountName,EmailAddress,LastLogonDate | Sort-Object Name
# show the result on screen
$result | Format-Table -AutoSize
# and/or save to a new csv file
$result | Export-Csv -Path 'C:\pathtofile\filteredusers.csv' -NoTypeInformation
My code:
$searchOU = "OU=a,OU=b,OU=c,OU=d,OU=e,DC=f,DC=g,DC=com"
Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase $searchOU | sort name | ForEach- Object{
$group = $_
Get-ADGroupMember -Identity $group | Get-ADUser | Where-Object { $_.Enabled -eq $false} | ForEach-Object{
$user = $_
$uname = $user.Name
$gname = $group.Name
Write-Host "Removing $uname from $gname" -Foreground Yellow
Remove-ADGroupMember -Identity $group -Member $user -Confirm:$false #-whatif
}
}
It runs, but it's dog slow. Any suggestions on ways to make it run faster?
You need to remember that Get-ADGroupMember can return users, groups, and computers, not just user objects..
If you want to search for user objects only, you need to add a Where-Object clause there.
Unfortunately, while Get-ADUser has a -Filter parameter that enables you to find disabled users much more quickly than filtering afterwards on the collection of users, using a filter while piping user DN's to it will totally ignore the pipeline and collect all users that are disabled..
So, in this case, we're stuck with appending a Where-Object clause.
You could change your code to rule out all objects from Get-ADGroupMember that are not uders:
$searchOU = "OU=a,OU=b,OU=c,OU=d,OU=e,DC=f,DC=g,DC=com"
Get-ADGroup -Filter "GroupCategory -eq 'Security'" -SearchBase $searchOU | Sort-Object Name | ForEach-Object {
$group = $_
Get-ADGroupMember -Identity $group | Where-Object { $_.objectClass -eq 'user' } |
Get-ADUser | Where-Object { $_.Enabled -eq $false} | ForEach-Object {
Write-Host "Removing $($_.Name) from $($group.Name)" -Foreground Yellow
Remove-ADGroupMember -Identity $group -Member $_ -Confirm:$false #-whatif
}
}
The above removes one disabled user at a time and for each of them writes a line on the console.
You could make it work faster if you can cope with getting a different output on screen like this:
$searchOU = "OU=a,OU=b,OU=c,OU=d,OU=e,DC=f,DC=g,DC=com"
$result = foreach ($group in (Get-ADGroup -Filter "GroupCategory -eq 'Security'" -SearchBase $searchOU)) {
$users = Get-ADGroupMember -Identity $group | Where-Object { $_.objectClass -eq 'user' } |
Get-ADUser | Where-Object { $_.Enabled -eq $false}
if ($users) {
# the Remove-ADGroupMember cmdlet can take an array of users to remove at once
Remove-ADGroupMember -Identity $group -Member $users -Confirm:$false #-whatif
# output an object that gets collected in variable $result
[PsCustomObject]#{Group = $group.Name; RemovedUsers = ($users.Name -join '; ')}
}
}
# if you like, output to console as table
$result | Sort-Object Group | Format-Table -AutoSize -Wrap
# or write to CSV file
$result | Export-Csv -Path 'D:\Test\RemovedUsers.csv' -NoTypeInformation
This script below works, but every attempt I make to have it cycle through all my domain controllers fail. How do I add a array to go through all these OUs on all my domain controllers. Thanks in advance!
$OUs= “OU=Test1,OU=Test1,OU=Test1,OU=Test1,OU=All Users,DC=domain,DC=local",
"OU=Test2,OU=Test2,OU=Test2,OU=All Users,OU=Test2,DC=domain,DC=local",
"OU=Test3,OU=Test3,OU=Test3,OU=All Users,OU=Test3,DC=domain,DC=local",
"OU=test4,OU=test4,OU=test4,OU=All Users,OU=test4,DC=domain,DC=local",
"OU=Test5,OU=test5,OU=Test5,OU=All Users,OU=test5,DC=domain,DC=local”
$OUs | ForEach-Object
{
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $_ -Properties Name,SamAccountName,LastLogonDate |
Where-Object {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)}
} |
Sort LastLogonDate |
Format-Table -Property Name,SamAccountName,LastLogonDate, DistinguishedName |
Out-String
Below you have now an array of your OUs. Please try whether that works for you now.
$OUs= #(
“OU=Test1,OU=Test1,OU=Test1,OU=Test1,OU=All Users,DC=domain,DC=local",
"OU=Test2,OU=Test2,OU=Test2,OU=All Users,OU=Test2,DC=domain,DC=local",
"OU=Test3,OU=Test3,OU=Test3,OU=All Users,OU=Test3,DC=domain,DC=local",
"OU=test4,OU=test4,OU=test4,OU=All Users,OU=test4,DC=domain,DC=local",
"OU=Test5,OU=test5,OU=Test5,OU=All Users,OU=test5,DC=domain,DC=local”
)
I would also suggest to break your line after every pipe in order to cut the line. That makes it far easier to read for you, plus your colleagues.
$OUs | ForEach-Object
{
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $_ -Properties Name,SamAccountName,LastLogonDate |
Where-Object {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)}
} |
Sort LastLogonDate |
Format-Table -Property Name,SamAccountName,LastLogonDate, DistinguishedName |
Out-String
You mention cycling through your domain controllers, but then you go on to ask about OUs. I suspect you want DC's, because each DC might have a different Last Logon Time for the user.
You can omit the -SearchBase and search all OU's, if you're looking to get this data for all users.
$Domains = Get-ADDomainController -Filter * #Note, this shows all DCs- you may have some without ADWS Installed, which won't handle the WHERE.
foreach ($domain in $Domains) {
Get-ADUser -Filter {Enabled -eq $TRUE} -Server $domain -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)} |
Export-CSV -Path 'UsersNotRecentlyLoggedIn.CSV' -Append
}
If you only want one DC, but all OUs
$Domains = Get-ADDomainController -Discover -Service ADWS
foreach ($domain in $Domains) {
Get-ADUser -Filter {Enabled -eq $TRUE} -Server $domain -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)} |
Export-CSV -Path 'UsersNotRecentlyLoggedIn.CSV' -Append
}
I need to use PowerShell to list users that are enabled, have never logged on or have not logged on in 60 days.
The below is what I've come up with having never used PowerShell previously, however clearly there is something wrong in my understanding as it just spouts out a bunch of different error messages.
Get-ADUser -Filter { Enabled -eq $true } -Properties LastLogonDate | where { ($_.LastLogonDate.AddDays(60) -lt $(Get-Date)) -or ( -not $_.LastLogonDate-like "*")) } | Select-Object SamAccountName | Format-Table
try this
Get-ADUser -Filter { Enabled -eq $true } -Properties LastLogonDate | where{ (($_.LastLogonDate.AddDays(60) -lt $(Get-Date)) -or ( -not $_.LastLogonDate-like "*")) } | Select-Object SamAccountName | Format-Table
your brackets werent correct, more specifically this bracket is extra
( -not $_.LastLogonDate-like "*")) // extra closing bracket
Taking my comment and making it an answer:
Get-ADUser -Filter { Enabled -eq $True } -Properties LastLogonDate |
#Tests whether LastLogonDate is older than 60 days or if it's $Null
Where-Object { $_.LastLogonDate -lt (Get-Date).AddDays(-60) -or
-not $_.LastLogonDate } |
Select-Object -Property SamAccountName |
Format-Table