Get AD Groups where the Owner is disabled with Powershell - powershell

This are the lines where Powershell gets all the groups in AD
Get-ADGroup -Filter * -Properties SamAccountName, managedBy, Name, Description, GroupCategory |
Select-Object SamAccountName, #{Name = 'ManagedBy'; Expression = { (Get-ADUser -Identity $_.managedBy -Properties DisplayName).DisplayName }},Name, Description, GroupCategory
What I'm trying to accomplish is to get only the AD groups where the owner Enabled property is set to disabled, something like the following but I cannot complete the logic
Get-ADGroup -Filter * -Properties SamAccountName, managedBy, Name, Description, GroupCategory |
Where (Get-ADUser -Filter "DisplayName -eq '$($_.DisplayName)'" | Select SamAccountName, Enabled -eq "false") |
Select-Object SamAccountName, #{Name = 'ManagedBy'; Expression = { (Get-ADUser -Identity $_.managedBy -Properties DisplayName).DisplayName }},Name, Description, GroupCategory
EDIT:
Applying jfrmilner's answer I get the following error
Get-ADUser : Cannot find an object with identity: 'CN=example,OU=example,OU=User Archive,DC=example,DC=example' under: 'DC=example,DC=example'.
At line:2 char:18
+ Where-Object { !(Get-ADUser -Identity $_.ManagedBy).Enabled } |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=exampl...,DC=example,DC=nexample:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

This will return only AD Groups where the ManagedBy User is Disabled:
Get-ADGroup -LDAPFilter "(ManagedBy=*)" -Properties ManagedBy, Description | Where-Object { !(Get-ADUser -Identity $_.ManagedBy).Enabled }

Related

Unable to export Powershell results

I'm completely new to Powershell and trying to learn as I go. I have a requirement to find all AD users whose passwords have not been reset within the last 365 days, I also need to pull various other fields such as lastlogontimestamp, manager, cn, distinguishedname etc. I have tried the code below and it will show some results in the powershell window but as I have quite a few columns I really need to export - however whenever I try to export I get the following error:
Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
At line:6 char:12
+ $outList | Export-Csv -path D:\scripts\test.xml -NoTypeInformation
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
Code I am using displayed below. Any help much appreciated.
`Get-AdUser -Filter 'Enabled -eq $True' -Properties Name, PasswordLastSet, PasswordNeverExpires, SamAccountName, accountExpires, Company, Description, cn, distinguishedName, info,lastLogonTimestamp, manager |
Where-Object {
$_.PasswordLastSet -lt (Get-Date).AddDays(-365)
} |
Format-Table Name, SamAccountName, PasswordLastSet, PasswordNeverExpires, Company, Description, cn, distinguishedName, info, lastLogonTimestamp, manager
$outList | Export-Csv -path D:\scripts\test.xml -NoTypeInformation
When you run the Get-ADUser command it returns certain properties by default - you only need to specify the non-standard properties that you require. In your case there is no need to specify name and SamAccountName.
$outList = Get-AdUser -Filter 'Enabled -eq $True' -Properties PasswordLastSet, PasswordNeverExpires, accountExpires, Company, Description, cn, distinguishedName, info,lastLogonTimestamp, manager | Where-Object { $_.PasswordLastSet -lt (Get-Date).AddDays(-365)}
The command Format-Table only refers screen output. To select properties from an object, use Select-Object
$outList | Select-Object Name, SamAccountName, PasswordLastSet, PasswordNeverExpires, Company, Description, cn, distinguishedName, info, lastLogonTimestamp, manager | Export-Csv -Path D:\scripts\test.csv -NoTypeInformation
TThe above as a one-line command:
Get-AdUser -Filter 'Enabled -eq $True' -Properties PasswordLastSet, PasswordNeverExpires, accountExpires, Company, Description, cn, distinguishedName, info,lastLogonTimestamp, manager | Where-Object { $_.PasswordLastSet -lt (Get-Date).AddDays(-365)} | Select-Object Name, SamAccountName, PasswordLastSet, PasswordNeverExpires, Company, Description, cn, distinguishedName, info, lastLogonTimestamp, manager | Export-Csv -Path C:\temp\test.csv -NoTypeInformation

Exclude specific OUs from Password Expiration Notification

Quick question guys, I'm updating a PS script that notifies users when their AD password is about to expire to exclude/Omit certain OUs from the notification. Example: Exclude "RemoteUsers" and "AppUsers" I have created a variable $Searchxyzbase="DC=example,DC=com" at the beginning of the script followed by the following:
# Get Enabled Users From AD RemoteUsers and AppUsers OU
Import-Module ActiveDirectory
$users = get-aduser -SearchBase $Searchxyzbase -Filter {(enabled -eq $true) -and (passwordNeverExpires -eq $false)} | -properties sAMAccountName, displayName, PasswordNeverExpires, PasswordExpired,
PasswordLastSet, EmailAddress, lastLogon, whenCreated
$DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
I know I suppose to be passing the following but not sure exactly where in the code.
? {$_.distinguishedname -notmatch 'OU=RemoteUsers|OU=AppUsers'}
I added it as follows:
# Get Enabled Users From AD RemoteUsers and AppUsers OU
Import-Module ActiveDirectory
$users = get-aduser -SearchBase $Searchxyzbase -Filter {(enabled -eq $true) -and
(passwordNeverExpires -eq $false)} | ? {$_.distinguishedname -notmatch 'OU=RemoteUsers|OU=AppUsers'} -properties sAMAccountName, displayName, PasswordNeverExpires,
PasswordExpired,
PasswordLastSet, EmailAddress, lastLogon, whenCreated
$DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
When I execute the code, it runs and return the following error:
`Where-Object : A parameter cannot be found that matches parameter name 'properties'.
At C:\code\ps.ps1:69 char:176
+ ... inguishedname -notmatch 'OU=RemoteUsers|OU=AppUsers'} -properties sAMAcco ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.WhereObjectCommand`
Doug suggestion worked. Thanks

msExchDelegateListBL attribute - The attribute cannot be modified because it is owned by the system

When attempting to clear msExchDelegateListBL for AD User then I got the following the error message.
Get-ADUser -Identity "User01" -Properties * | set-aduser -clear msExchDelegateListBL
Message :
set-aduser : The attribute cannot be modified because it is owned by the system
At line:1 char:49
+ ... ity "User01" -Properties * | set-aduser -clear msExchDelegateListBL
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=User01...,DC=corp:ADUser) [Set-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8369,Microsoft.ActiveDirectory.Management.Commands.SetADUser
LAST UPDATE :
$userDN = Get-ADUser -Filter {(Enabled -eq $true -and sAMAccountName -like "TEST*") -or (Enabled -eq $true -and sAMAccountName -like "PROD*")} -SearchBase "OU=COMPANY,DC=contoso,DC=local" -SearchScope Subtree -Properties * |select-object distinguishedname,samaccountname
foreach($userToClean in $userDN) {
$delegates = Get-ADUser $userToClean.samaccountname -Properties msExchDelegateListBL | select -ExpandProperty msExchDelegateListBL
Write-Host “======================================================”
write-host “List of Delegated accounts that are backlinked:” $Delegates
Write-Host “======================================================”
foreach ($delegate in $delegates) {
Set-ADUser $delegate -Remove #{msExchDelegateListLink = "$($userToClean.distinguishedname)"}
}
Write-Host “======================================================”
Write-Host “If the following get-aduser cmdlet searching for backlinds is empty, then all delegated backlinks have been removed”
Get-ADUser $userToClean.samaccountname -Properties msExchDelegateListBL | select -ExpandProperty msExchDelegateListBL
Write-Host “======================================================”
}
The msExchDelegateListBL attribute is adjusted by the system after a user is removed from (or added to) the msExchDelegateListLink of the delegate.
When users are granted permission to a shared mailbox, the default behaviour of automapping means that the shared mailbox has msExchDelegateListLink set to the DN of the users, and the backlink property (msExchDelegateLinkListBL hidden in AD by default) on each user is populated with the DN of the shared mailbox. Whenever the link attribute is updated, the backlink is automatically updated.
I found a good read about that, including PowerShell code.
For your question I suggest to scroll down to To remove all BLs all at once chapter and adapt the code in there to suit your needs as you have done in your edit.
Personally, I would change the top line in your code into
$userDN = Get-ADUser -Filter "Enabled -eq 'True'" -SearchBase "OU=COMPANY,DC=contoso,DC=local" -SearchScope Subtree |
Where-Object { $_.SamAccountName -match '^(TEST|PROD)' }
since user properties SamAccountName and DistinguishedName are returned by the Get-ADUSer cmdlet by default.

Powershell list group names for each user in array

I want to return the group names in a semicolon delimited list for each AD user in an array. Here is what I have so far:
$ADuser = Get-ADUser -filter * -Properties * | ? {$_.employeeNumber -eq " 9408" -or $_.employeeNumber -eq "3816"} | Select-Object Name,SamAccountName,UserPrincipalName,DisplayName,GivenName,Surname,description,mail,Enabled,HomeDirectory,distinguishedname,MemberOf
foreach($user in $ADuser)
{
$Groups = forEach ($group in $ADuser.memberOf)
{
(Get-ADGroup $group).name
}
$groupStr = $Groups -join ";"
$ADuser = $ADuser | Select-Object Name,SamAccountName,UserPrincipalName,DisplayName,GivenName,surname,description,mail,Enabled,HomeDirectory,distinguishedname,#{n='Groups';e={$groupStr}}
}
This code works fine when $ADuser contains a single user. When $ADuser contains more than one user, I get the following error each time it tries to set Groups:
Get-ADGroup : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At line:8 char:22
+ (Get-ADGroup $group).name
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADGroup],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
I expect the output to be like this for each $ADuser:
Name : John.Doe
SamAccountName : John.Doe
UserPrincipalName : John.Doe#mydomain.com
DisplayName : John Doe
GivenName : John
Surname : Doe
description : Joe is a person
mail : John.Doe#mydomain.com
Enabled : True
HomeDirectory : \\fileserver\homefolders\John.Doe
distinguishedname : CN=John.Doe,OU=People,OU=my,DC=domain
Groups : Group1;Group2;Group3;Group4
Looks like you have messed up with these two variables: $ADUsers and $users.
$ADuser = Get-ADUser -filter * -Properties * | ? {$_.employeeNumber -eq " 9408" -or $_.employeeNumber -eq "3816"} | Select-Object Name,SamAccountName,UserPrincipalName,DisplayName,GivenName,Surname,description,mail,Enabled,HomeDirectory,distinguishedname,MemberOf,Groups
$Results = New-Object System.Collections.ArrayList
foreach($user in #($ADuser))
{
$Groups = forEach ($group in #($user.memberOf))
{
(Get-ADGroup $group).name
}
$user.Groups = $Groups -join ';'
[Void]$Results.Add($user)
}
$Results
Kirill Pashkov's helpful answer solves your immediate problem.
To take a step back:
Your symptoms suggest that you're running on PSv2, which has the following implications:
Member-access enumeration (PSv3+) isn't available; that is, if $ADuser is an array (a collection), you cannot use .memberOf to implicitly collect the .memberOf property values of its elements.
A foreach (...) { ... } loop executes its loop body even if the value to enumerate is $null - in PSv3+ the loop body isn't executed at all.
That said, your code can presumably be reduced to this one command:
Get-ADUser -Properties * |
? {$_.employeeNumber -eq " 9408" -or $_.employeeNumber -eq "3816"} |
Select-Object Name,
SamAccountName,
UserPrincipalName,
DisplayName,
GivenName,
Surname,
description,
mail,
Enabled,
HomeDirectory,
distinguishedname,
#{
n='Groups';
e={ ($_.memberOf | Get-AdGroup | Select-Object -ExpandProperty Name) -join ";" }
}

Getting AD groups and their users

I've been trying to get a list of all the groups in our AD environment (with the description) and their members and output it to a CSV file. Ideally the users would be shown under their group. The script I've been trying to use is:
Import-Module ActiveDirectory
Get-ADGroup -Filter * -Properties Description |
Select-Object Name, Description |
ForEach-Object {
Get-ADGroupMember -Identity $_.DistinguishedName -Recursive |
Get-ADObject -Properties SamAccountname, Title, Department |
Select-Object Name, SamAccountName, Title, Department, DistinguishedName, ObjectClass
} | Export-Csv -Path c:\temp\ADGrab.csv -NoTypeInformation
The error I keep getting is as follows:
Get-ADGroupMember : Cannot validate argument on parameter 'Identity'. The argument
is null or empty. Supply an argument that is not null or empty and then try the
command again.
At C:\Users\j_kennedy_ta\AppData\Local\Temp\9\2898ceb2-a6cf-4fbf-9341-e651dad2145d.ps1:4 char:28
+ Get-ADGroupMember -Identity <<<< $_.distinguishedname -Recursive |
+ CategoryInfo : InvalidData: (:) [Get-ADGroupMember], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
Without the nasty Select-Object and with group information in the CSV file:
Import-Module ActiveDirectory
Get-ADGroup -Filter * -Properties Description |
ForEach-Object {
# Store for later use
$groupName = $_.Name
$groupDescription = $_.Description
Get-ADGroupMember -Identity $_.DistinguishedName -Recursive |
Get-ADObject -Properties SamAccountname, Title, Department |
Select-Object Name, SamAccountName, Title, Department, DistinguishedName, ObjectClass, ` # Mind the gap
# Calculated properties with group information
#{ name = "GroupName"; expression = $groupName }, `
#{ name = "GroupDescription"; expression = $groupDescription }
} | Export-Csv -Path c:\temp\ADGrab.csv -NoTypeInformation