I want to exclude some users inside AD.
e.g
TST292736ca
PRD1212ca
PRD212132121ca
PRD293873
PRD122
TST141444
TST122
cyberhw12
and so on
My question is : I want to exclude "Users starting with TST and ending with ca" , "Users starting with PRD and ending with ca" , "starting with cyber" users.
script :
get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
I would do it something like that: fill $ADUsersExcluded with excluded users and with foreach and if fill new array with users $filteredUsers.
[array]$ADUsersExcluded = $null
$ADUsersExcluded += Get-ADUser -Filter {SamAccountName -like "TST*ca"}
$ADUsersExcluded += Get-ADUser -Filter {SamAccountName -like "PRD*ca"}
$ADUsersExcluded += Get-ADUser -Filter {SamAccountName -like "cyber*"}
$AllUsers = Get-ADUser -Filter * -Properties Name,PasswordNeverExpires,PasswordExpired,PasswordLastSet,EmailAddress | Where-Object {$_.Enabled -eq "True"} | Where-Object { $_.PasswordNeverExpires -eq $false } | Where-Object { $_.passwordexpired -eq $false }
[array]$filtered = $null
foreach($user in $AllUsers) {
if($ADUsersExcluded -notcontains $user){
$filteredUsers += $user
}
}
$filteredUsers
First, dont forget to import AD module. Check condition values.
[array] $ADExcludedUser = 'User1', 'User2', 'User3'
$AllUsers = Get-ADUser -Filter * -Properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress | Where-Object { ( $_.Enabled -eq "True" ) -and ( $_.PasswordNeverExpires -eq $false ) -and ( $_.name -notin $ADExcludedUser ) }
$AllUsersExceptExcluded = $AllUsers | where-object { $_.name -notin $ADExcludedUser }
write-host -object $AllUsersExceptExcluded
I would use a regex -notmatch for this:
Get-ADUser -Filter "Enabled -eq $true" -Properties PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |
Where-Object { $_.PasswordNeverExpires -eq $false -and $_.PasswordExpired -eq $false -and $_.Name -notmatch '^(TST|PRD).*ca$|^cyber' }
If you need case-sensitivity, change notmatch into -cnotmatch
Related
First script I have tried to put together. Im trying to get a new variable with ad user name and ad computer by comparing user name property and description properties. I don't know how to pull the properties I want into the new variables based on a compare-object or match. The description property has a setup of username - ######## numbers very.
Variables used (date tell expire)
$SevenDayWarnDate, $ThreeDayWarnDate, $OneDayWarnDate
AD user
$7, $3, $1 -properties "Name", "PasswordExpiry
AD computer
$comp "Name", "Description"
I was then going to make a pop up on user computer based on expiring passwords.
Below is what I was trying to do but im not sure if the needed information was passed as computer filed comes back empty.
$SevenDayWarnDate = (get-date).adddays(7).ToLongDateString()
$7= Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } `
-Properties "Name", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name", `
#{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring() }} `
|Where-object -Property PasswordExpiry -EQ $SevenDayWarnDate
$comp = Get-Adcomputer -Filter {Enabled -eq $True} -SearchBase "OU=,DC=" -properties "Name", "Description" `
| Select-Object -Property "Name", "Description"
Compare-Object -ReferenceObject $7 -DifferenceObject $comp -IncludeEqual -ExcludeDifferent -PassThru |
ForEach-Object {
[PSCustomObject]#{
Name = $_.name
Computer = ($comp.name | Where-Object Description -match $_.name).Directory
}
}
Working code based on Santiago Squarzon below.
$dayArray= #()
$dayArray=#(7,3,1)
foreach ($day in $dayArray)
{
$SevenDayWarnDate = (get-date).adddays($day).ToLongDateString()
$filter = "Enabled -eq '$True' -and PasswordNeverExpires -eq '$False' -and PasswordLastSet -gt '0'"
$computerArray= #()
$users = Get-ADUser -Filter $filter -Properties "Name", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object Name, #{
Name = "PasswordExpiry"
Expression =
{
[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring()
}
} | Where-object -Property PasswordExpiry -EQ $SevenDayWarnDate
# => It might be better to use:
# PasswordExpiry -ge [datetime]::Now -and PasswordExpiry -le $sevenDayWarnDate
# Find the computers each user is using
$result = foreach($user in $users)
{
$temp=$user.Name
if ($comp = Get-ADComputer -Filter "Description -like '*$temp*'" -Properties Description)
{
[PSCustomObject]#{
Name = $user.Name
PasswordExpiry = $user.PasswordExpiry
ComputerName = $comp.Name
ComputerDescription = $comp.Description
}
$tmpArray= #()
$tmpArray= $comp.Name.Split(" ")
foreach($item in $tmparray)
{
$computerArray += $item
}
$tmpArray = $Null
# }
}
continue
}
foreach($computer in $computerArray)
$tmpMessage =
$tmpMessageTitle =
{Send-RDUserMessage -HostServer $env:COMPUTERNAME -UnifiedSessionID 1 -MessageTitle $tmpMessageTitle -MessageBody $tmpMessage
}
$result | Format-Table
}
Based on the comments and the code in question, I'm guessing this is what you're looking for. There is no need to use Compare-Object, you can simply query Active Directory to get the user's computer based on the Description property.
$SevenDayWarnDate = [datetime]::Now.AddDays(7)
$filter = "Enabled -eq '$True' -and PasswordNeverExpires -eq '$False' -and PasswordLastSet -gt '0'"
$users = Get-ADUser -Filter $filter -Properties "Name", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object Name, #{
Name = "PasswordExpiry"
Expression = {
[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")
}
} | Where-object -Property PasswordExpiry -EQ $SevenDayWarnDate
# => It might be better to use:
# {$_.PasswordExpiry -ge [datetime]::Now -and $_.PasswordExpiry -le $sevenDayWarnDate}
# Find the computers each user is using
$result = foreach($user in $users)
{
if($comp = Get-ADComputer -LDAPFilter "(description=$($user.Name))" -Properties Description)
{
[PSCustomObject]#{
Name = $user.Name
PasswordExpiry = $user.PasswordExpiry
ComputerName = $comp.Name
ComputerDescription = $comp.Description
}
continue
}
Write-Host "No computer was found for User: $($user.Name)"
}
$result | Format-Table
I'm writing a script to check if user from specific OU are not members of Group 1 or Group 2 or Group 3 or Group 4.
I have try this but some users are getting listed while they are not suppose to be.
get-aduser -filter * -searchbase "$Ou" | where-object {((get-aduser $_.samaccountname -properties memberof).memberof -ne "$grp1") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp2") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp3") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp4")} | Select SamAccountName
Not sure I follow, but it sounds like you're asking for something like this:
$ou = 'OU=crowleytest,DC=contoso,DC=local'
$group1 = 'CN=group1,OU=crowleytest,DC=contoso,DC=local'
$group2 = 'CN=group2,OU=crowleytest,DC=contoso,DC=local'
$group3 = 'CN=group3,OU=crowleytest,DC=contoso,DC=local'
$group4 = 'CN=group4,OU=crowleytest,DC=contoso,DC=local'
$users = Get-ADUser -SearchBase $ou -Filter * -Properties memberof
$results = $users | where {
$_.memberof -notcontains $group1 -and
$_.memberof -notcontains $group2 -and
$_.memberof -notcontains $group3 -and
$_.memberof -notcontains $group4
}
$results
e - This filter could also be moved to the left into the -filter parameter for better performance, but that requires a different syntax. If you're not working with a huge list of users, the example above should suffice.
I am a novice to powershell and starting to learn the syntax and what logic is needed, but I have given this a good go.
I need to pop in a conditional field that does the below
If users are a member of the "Domain Admins" group, then show "Administrator"
If users are a member of the "ReadOnlyAccess" group, then show "Read Only"
But my script doesn't quite do this and I wandered how my script could be changed to get what I need it to do.
This is my script below:
Import-Module ActiveDirectory
$OUPath = "OU=1_Users,DC=DGDomain,DC=Local"
$filepath = "C:\temp\users.csv"
$readonlygroup = "ReadOnlyAccess"
$readonlygroupmembers = Get-ADGroupMember -Identity $readonlygroup | Get-ADUser -Properties SamAccountName | Select SamAccountName
$admingroup = "Domain Admins"
$admingroupmembers = Get-ADGroupMember -Identity $admingroup | Get-ADUser -Properties SamAccountName | Select SamAccountName
$users = Get-ADUser -Filter * -Properties * -SearchBase $OUPath |
Where-Object { $_.Enabled -eq $true } |
Select SamAccountName
Get-ADUser -Filter * -Properties * -SearchBase $OUPath |
Where-Object { $_.Enabled -eq $true } |
Select SamAccountName,
DisplayName,
#{Label = "Access Level"
Expression = {
foreach ($user in $users) {
if ($readonlygroupmembers -contains $users)
{ "Read Only" }
else {
if ($admingroupmembers -contains $users)
{ "Administrator" }
else
{ "None" }
}
} } } |
Export-csv $filepath -NoTypeInformation
This should do the trick:
$OUPath = "OU=1_Users,DC=DGDomain,DC=Local"
$filepath = "C:\temp\users.csv"
$readonlygroup = "ReadOnlyAccess"
$readonlygroupmembers = (Get-ADGroupMember -Identity $readonlygroup | Get-ADUser -Properties SamAccountName).SamAccountName
$admingroup = "Domain Admins"
$admingroupmembers = (Get-ADGroupMember -Identity $admingroup | Get-ADUser -Properties SamAccountName).SamAccountName
$users = Get-ADUser -Filter { Enabled -eq $true } -SearchBase $OUPath -Properties DisplayName
foreach ($user in $users) {
if ($user.SamAccountName -in $admingroupmembers) { $groupMembership = 'DomainAdmin'}
elseif ($user.SamAccountName -in $readonlygroupmembers) { $groupMembership = 'ReadOnly' }
else {$groupMembership = 'None'}
[PSCustomObject]#{
DisplayName = $user.DisplayName
SamAccountName = $user.SamAccountName
AccessLevel = $groupMembership
}
}
Export-csv $filepath -NoTypeInformation
I'm currently getting a list of managers in AD from
Get-ADUser -Filter "DirectReports -like '*'" -Properties *
Whats the easiest way to scan this against the entire AD domain to see if they are a manager?
Not working code:
$Users = Get-ADUser -Filter * -Properties *
Foreach ($User in $Users) {
If (Get-AdUser -Identity $User -Filter "DirectReports -like '*' -eq $True")
{Write-Host "$User is a Manager"} Else {Write-Host "$User is NOT a Manager"}
}
Thanks
Do you mean this?
Get-ADUser -Filter * -Properties directReports | ForEach-Object {
$isManager = ($_.directReports | Measure-Object).Count -gt 0
$_ | Select-Object name,
#{Name = "Manager"; Expression = {$isManager}}
}
I have written the below script to list all users who are "contractors"(employeetype=contractors) and not part of a particular group like "domain contractors" But it is not working, can some one help :)
$adusers = get-aduser -filter * -searchbase "OU=test,dc=domain,dc=com" -properties employeetype | where {($_.employeetype -like "contractor") -AND ($_.enabled -eq $true)}
foreach ($aduser in $adusers){
$contractorsDn = (Get-ADGroup 'domaincontractors').DistinguishedName
Get-ADUser $aduser -LDAPFilter "(!(memberof=$contractorsDn))"
}
$users = get-aduser -filter {(employeetype -like "contractor") -AND (enabled -eq $true)} -searchbase "dc=domain,dc=COM" -properties employeetype
$group = "Domaincontractors"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty DistinguishedName
ForEach ($user in $users) {
If ($members -contains $user) {
write-host "$user exists" -ForegroundColor Red
} Else {
write-host "$user doesnt exist" -ForegroundColor Green
}}