I have a list of user samaccount names that I need query for the manager attribute. Then I need to query the results (DN) of the manger account for the accounts directs reports, there will be multiple on each account. Then I need to search for direct report that contains "(admin)" in it (in the DN). I need that full DN and none that dont match (there should only be one)
My input is currently a get-aduser for testing. Everything works up to the "where"
I think I'm very close I just cant seem to get the last step
Get-Aduser -filter {cn -like "ea8f"} -Properties directreports -server domain.com |
select-Object -ExpandProperty directreports | Where $_.directreports -Contains "(admin)"
Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:2 char:57
+ ... Object -ExpandProperty directreports | Where $_.directreports -Contai ...
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Where-Object], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand
Ok, I have not tested this at the moment, but I think this may work:
# read the users SamAccountNames from the file and loop through
$result = Get-Content -Path 'THE LIST.txt' | ForEach-Object {
# get the Manager attribute
$managerDN = Get-ADUser -Identity $_ -Properties Manager | Select-Object -ExpandProperty Manager
if ($managerDN) {
# if set, use Get-ADUser on the manager DN and try and find the DirectReports that contain the string "(admin)"
Get-ADUser -Identity $managerDN -Properties DirectReports |
Select-Object -ExpandProperty DirectReports |
Where-Object { $_ -match '\(admin\)'} |
ForEach-Object {
# output this DN
$directReports
}
}
}
# output to console
$result
This is what ended up working for me 100%, thanks to everyone who contributed I used something from everyone.
$input = Get-Content -Path $path
$results = #()
#Process each account
ForEach ($user in $input)
{
$current = get-aduser -Filter {samaccountname -like $user} -server $server -Properties Directreports |
Select-Object -ExpandProperty DirectReports |
Where-Object { $_ -match '\(admin\)'}
$dr = New-Object -TypeName PSObject
$dr | Add-Member -MemberType NoteProperty -Name SAM -Value $user
$dr | Add-Member -MemberType NoteProperty -Name Password -Value "z,7'*FBU+"
$dr | Add-Member -MemberType NoteProperty -Name TargetOU -Value $current.Substring($current.IndexOf('OU='))
$dr
$results += $dr
}
$results
Related
I'm trying to figure out the reason why I can run the script using variable $groups with Get-Content but it wont work if variable $groups goes with Get-ADGroup list I did below...
Block that works:
$groups = Get-Content C:\groups.csv
$results = #()
$file = "C:\Usuarios_Grupos_Darwin_AD.csv"
foreach($Group in $Groups) {
$results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Identity $_.SamAccountName -Properties Enabled,Name} | Select #{Expression={$Group};Label=”Group Name”},SamAccountName,Name,Enabled
}
$results | export-csv -notypeinformation -Delimiter ";" -path $file
Block that's not working:
(only the first line has been changed)
$groups = Get-ADGroup -Filter {Name -like '*Darwin*'} -Properties * | select -property Name
$results = #()
$file = "C:\Usuarios_Grupos_Darwin_AD.csv"
foreach($Group in $Groups) {
$results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Identity $_.SamAccountName -Properties Enabled,Name} | Select #{Expression={$Group};Label=”Group Name”},SamAccountName,Name,Enabled
}
$results | export-csv -notypeinformation -Delimiter ";" -path $file
Here is the error:
Get-ADGroupMember : Cannot bind parameter 'Identity'. Cannot create object of type "Microsoft.ActiveDirectory.Management.ADGroup". The adapter cannot set the value of property
"Name".
At line:11 char:34
+ $results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Id ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADGroupMember], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
I'm trying to embed the output list all in one script without having to generate csv with another script.
Thanks in advance !!
A few notes about your code:
the -Filter parameter should be a string, not a scriptblock
using $results += is very costly because the entire array needs to be rebuilt in memory on each addition
Get-ADGroupMember can return also computer and (when not used with -Recursive) also group objects, not just users, so you cannot pipe directly to Get-ADUser
never use -Properties * if all you want is one single property
Try this:
# Get-ADGroup already returns objects with these properties:
# DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
$groups = Get-ADGroup -Filter "Name -like '*Darwin*'"
$file = "C:\Usuarios_Grupos_Darwin_AD.csv"
# let PowerShell collect the objects for you instead of using +=
$results = foreach($Group in $Groups) {
# Get-ADGroupMember can return objects of type users and computers (also groups when used without -Recursive)
# so filter the result to get only user objects
$Group | Get-ADGroupMember -Recursive | Where-Object { $_.objectClass -eq 'user' } | ForEach-Object {
$_ | Get-ADUser | Select #{Name = 'Group Name'; Expression={$Group.Name}}, SamAccountName, Name, Enabled
}
}
$results | Export-Csv -Path $file -NoTypeInformation -Delimiter ";"
The following code query's AD for information on user accounts and is expected to export an excel file that contains the Name, Username, AccountEnabled(yes/no), Department, Description, LastLogonDate, and what groups every user in AD has. Currently the script works as intended except that under the users Groups, it does not list 'Domain User' on ANY user which they all contain. I am trying to determine why and how to fix.
Import-Module ActiveDirectory
$Report = #()
#Collect all users
$Users = Get-ADUser -Filter * -Properties Name, GivenName, SurName, SamAccountName, UserPrincipalName, MemberOf, Enabled, Department, Description, LastLogonDate -ResultSetSize $Null
# Use ForEach loop, as we need group membership for every account that is collected.
# MemberOf property of User object has the list of groups and is available in DN format.
Foreach($User in $Users){
$UserGroupCollection = $User.MemberOf
#This Array will hold Group Names to which the user belongs.
$UserGroupMembership = #()
#To get the Group Names from DN format we will again use Foreach loop to query every DN and retrieve the Name property of Group.
Foreach($UserGroup in $UserGroupCollection){
$GroupDetails = Get-ADGroup -Identity $UserGroup
#Here we will add each group Name to UserGroupMembership array
$UserGroupMembership += $GroupDetails.Name
}
#As the UserGroupMembership is array we need to join element with ‘,’ as the seperator
$Groups = $UserGroupMembership -join ‘, ‘
#Creating custom objects
$Out = New-Object PSObject
$Out | Add-Member -MemberType noteproperty -Name Name -Value $User.Name
$Out | Add-Member -MemberType noteproperty -Name UserName -Value $User.SamAccountName
$Out | Add-Member -MemberType noteproperty -Name Enabled -Value $User.Enabled
$Out | Add-Member -MemberType noteproperty -Name Department -Value $User.Department
$Out | Add-Member -MemberType noteproperty -Name Description -Value $User.Description
$Out | Add-Member -MemberType noteproperty -Name LastLogonDate -Value $User.LastLogonDate
$Out | Add-Member -MemberType noteproperty -Name Groups -Value $Groups
$Report += $Out
}
#Output to screen as well as csv file.
#$Report | Sort-Object Name | FT -AutoSize
$Report | Sort-Object Name | Export-Csv -Path "C:\Scripts\Output\users.csv" -NoTypeInformation -Encoding UTF8
You are not seeing it because it's the primary group for most users.
See this question for a better explanation.
https://serverfault.com/questions/955721/why-is-the-domain-users-group-missing-from-this-powershell-ad-query
As for your script it can probably be simplified a bit by using pipes and calculated properties.
$Users = Get-ADUser -Filter * -Properties Name, GivenName, SurName, SamAccountName, UserPrincipalName, MemberOf, Enabled, Department, Description, LastLogonDate -ResultSetSize $Null
$users | Select Name, #{Name='Username';Expression={$_.SamAccountName}}, Enabled, Department, Description, LastLogonDate, `
#{Name='Groups';Expression={
($_.MemberOf | foreach{ Get-AdGroup -Identity $_ } | select -expand name) -join ","
}}
And if you want it to run faster remove the Get-AdGroup command and replace it with a split/trim command.
Although that is a bit more janky, but a lot faster.
$users | Select Name, #{Name='Username';Expression={$_.SamAccountName}}, Enabled, Department, Description, LastLogonDate, `
#{Name='Groups';Expression={
($_.MemberOf | foreach {($_ -split ",")[0].TrimStart('CN=')}) `
}} | select -expand groups | Sort-Object
A more elegant way of creating a custom object like you are doing would be something like this.
[pscustomobject]#{
Username= "jdoe"
FullName = "John Doe"
}
I'm trying to collect folder permissions to a csv file with Powershell. My problem is that I'd need the results to contain both the SamAccountName and FileSystemRights.
I tried two different method. The first I came up with was a simple approach that gave me IdentityReference and FileSystemRights, but I couldn't find any working method that can get SamAccountName from IdentityReference.
The second one I found on the internet was much more sophisticated. It collects all the accounts that has access to the folder, but it doesn't show FileSystemRights and I couldn't figure out how to change it to do so.
My own solution
(Get-Acl "FolderPath").Access | Select-Object IdentityReference, FileSystemRights
The solution I found
Get-Acl $UncPath | Select-Object -ExpandProperty Access | Where-Object { (-not $_.IsInherited) -and ('NT AUTHORITY\SYSTEM','BUILTIN\Administrators','CREATOR OWNER' -notcontains $_.IdentityReference) } | Select-Object -ExpandProperty IdentityReference | ForEach-Object { $_.Translate('System.Security.Principal.SecurityIdentifier').Value } | Get-ADGroup -ErrorAction SilentlyContinue | get-adgroupmember | select-object SamAccountName | Format-Table | Out-String
Is there any working method that can get me a result where I can see SamAccountName and FileSystemRights?
Thank you in advance.
$UncPath = 'E:\temp\test'
$all = Get-Acl $UncPath |
Select -ExpandProperty Access |
Where-Object { (-not $_.IsInherited) -and ('NT AUTHORITY\SYSTEM','BUILTIN\Administrators','CREATOR OWNER' -notcontains $_.IdentityReference) } |
Select-Object #{ Name = 'Identity'; Expression = { $_.IdentityReference -replace "\w+\\(.+)", '$1' } }, FileSystemRights
# Here you can get Users ACL
$distinct_users = $all |
Select-Object Identity, #{ Name = 'sAMAccountName'; Expression = { (Get-ADUser -Identity $_.Identity -ErrorAction SilentlyContinue).sAMAccountName }}, FileSystemRights |
Where-Object sAMAccountName -ne $null
# Here we will expand group acls
$groups = $all |
Select-Object Identity, #{ Name = 'sAMAccountName'; Expression = { (Get-ADGroup -Identity $_.Identity -ErrorAction SilentlyContinue).sAMAccountName }}, FileSystemRights |
Where-Object sAMAccountName -ne $null
# now we will get groups membership
$group_users = #()
Foreach($group in $groups){
Get-ADGroupMember -Identity $group.Identity | ForEach-Object { $group_users += [PSCustomObject]#{
'Identity' = $group.Identity
'sAMAccountName' = $_.sAMAccountName
'FileSystemRights' = $group.FileSystemRights
} }
}
$everyone = $distinct_users + $group_users
$everyone | Export-Csv -Path D:\example.csv
Check $everyone variable it will contain 3 columns: Identity as it was in the ACL, sAMAccountName and FileSystem Rights.
good day to all.
I've been trying to get information about groups and subgroups in Active Directory
I've tried many variants like the one below,
What I essentially need is, to get a CSV of all the groups in AD that contain "infolink" in their name, and the columns I need are:
GiveName
SN
Username
Mail
Group
ManagedBy
But no matter how I put it I only get some of the things I need.
Does someone already have a bit of code that could make my life a bit easier? If so, I'd be immensely grateful.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "*Infolink*"} | select name -ExpandProperty name)
$Table = #()
$Record = #{
"Group Name" = ""
"Name" = ""
"Username" = ""
"mail" = ""
}
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "D:\Infolink.csv" -NoTypeInformation
Try this,
Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter "name -like '*Infolink*'" -Properties ManagedBy
$table = foreach ($group in $groups) {
$Arrayofmembers = Get-ADGroupMember -Identity $group -Recursive
$ArrayofmembersUsers = $Arrayofmembers | Get-ADUser -Properties Mail
$ArrayofmembersUsers | Add-Member -Name GroupInfoLinkName -MemberType NoteProperty -Value $group.Name -Force
$ArrayofmembersUsers | Add-Member -Name GroupInfoLinkManageBy -MemberType NoteProperty -Value $group.ManagedBy -Force
$ArrayofmembersUsers
}
$table | Select-Object -Property GivenName, SurName, SamAccountName, Mail, GroupInfoLinkName, GroupInfoLinkManageBy | Export-Csv "D:\Infolink.csv" -NoTypeInformation
Some Pointers..
Use the Filter on Get-ADGroup else you're getting all groups in AD and then filtering.
PSObject are great but if your Object already has the majority of the properties you require then Add-Member is helpful to add 1 or 2 more.
Many cmdlets have a Properties parameter, you'll see I've used this to include properties that were not included by default. Unfortunately Get-ADGroupMember is not one of those cmdlets so piping to Get-ADUser helps provide a workaround.
I am looking for help writing a powershell script that will query Active Directory and output a CSV.
This script will list all groups and all users and signify with a character when a user belongs to that group.
The output will look like this: https://imgur.com/1MfFv7Q
I've tried using dsquery and various other powershell methods, but none seem to work.
I'm hoping someone here will have a different perspective on this and be able to help out.
Thank you!
Update 1:
As requested, here's my code that I was trying to work with previously.
#Get a list of the groups
$groups = Get-ADGroup -filter * -Properties Name | Select Name
#iterate through groups array and append each with a comma
$output = ForEach ($g in $groups){
$topgroups.Add($g)
$topgroups.Add(",")
}
#for each group, find out if the user is part of that group
$output = ForEach ($g in $groups) {
$results = Get-ADGroupMember -Identity $g.name -Recursive | Get-ADUser -Properties enabled, SamAccountName, givenname, surname,physicalDeliveryOfficeName
ForEach ($r in $results){
New-Object PSObject -Property #{
GroupName = $g.Name
Username = $r.name
DisplayName = $r.displayname
}
}
}
$output | Export-Csv -path c:\temp\output.csv -NoTypeInformation
Update 2:
Added FTP Upload and some more information. Thanks again TheMadTechnician!
My goal is to get this information from each of my clients, import this into SQL with SSIS with a timestamp, and then I can do can do comparison through sql reporting.
Here's my script where it is currently:
New-Item c:\temp\audit -type directory
$Domain = (gwmi WIN32_ComputerSystem).Domain
$filename = $Domain + "_ADExport.csv"
$fileoutput = "c:\temp\audit\" + $filename
Remove-Item $fileoutput
$GroupRef = #{}
Get-ADGroup -filter * | ForEach{$GroupRef.Add($_.DistinguishedName,$_.Name)}
$Users = Get-ADUser -Filter * -Prop MemberOf, passwordlastset, LastLogonDate
ForEach($User in $Users){
$LineItem = [PSCustomObject]#{'Enabled'=$User.Enabled;'First Name'=$User.givenname;'Last Name'=$User.surname;'Location'=$User.physicalDeliveryOfficeName;'Domain'=$Domain;'SAMAccountName'=$User.samaccountname;'LastLoggedOn'=$User.lastlogonDate;'PasswordLastSet'=$User.passwordlastset}
$GroupRef.Values | ForEach{Add-Member -InputObject $LineItem -NotePropertyName $_ -NotePropertyValue ""}
$User.MemberOf | ForEach{$LineItem.$($GroupRef["$_"]) = "X"}
[Array]$Results += $LineItem
}
$Results|export-csv $fileoutput -notype
#we specify the directory where all files that we want to upload
$Dir="C:/temp/audit/"
#ftp server
$ftp = "ftp://8.8.8.8/"
$user = "test"
$pass = "ThisIsARea11yL0NgPa33Word"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#list every file
foreach($item in (dir $Dir "*.csv")){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
Update 3:
Good afternoon:
I've run into an issue where I am trying to restrict which OU this searches through:
$GroupRef = #{}
$OUPATH = (Get-ADOrganizationalUnit -Filter 'Name -like "CLIENT_GROUPS"' | FT DistinguishedName -HideTableHeaders | Out-String).Trim()
Get-ADGroup -SearchBase "$OUPATH" -Filter * | ForEach{$GroupRef.Add($_.DistinguishedName,$_.Name)}
The error is:
Exception setting "": "Cannot process argument because the value of argument "name" is not valid. Change the value of
the "name" argument and run the operation again."
At C:\Users\f12admin\Desktop\test.ps1:23 char:42
+ $User.MemberOf | ForEach{$LineItem.$($GroupRef["$_"]) = "X"}
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
All you need are Get-ADUser, Get-ADGroup, New-Object, Add-Member, and Export-CSV. I'd build a hashtable of groups linking their distinguishedname and their displayname. Then I'd get a list of all users, create a custom object for each user, loop through the list of groups and add a property to the custom object for each group. Then loop through the user's MemberOf property and set the associated property on the custom object to "X" for everything there. Collect all of the custom objects in an array, and export it to a csv.
This isn't tested, but here's the theory...
$GroupRef = #{}
Get-ADGroup -filter * | ForEach{$GroupRef.Add($_.DistinguishedName,$_.Name)}
$Users = Get-ADUser -Filter * -Prop MemberOf
ForEach($User in $Users){
$LineItem = [PSCustomObject]#{'DisplayName'=$User.DisplayName;'SAMAccountName'=$User.samaccountname}
$GroupRef.Values | ForEach{Add-Member -InputObject $LineItem -NotePropertyName $_ -NotePropertyValue ""}
$User.MemberOf | ForEach{$LineItem.$($GroupRef["$_"]) = "X"}
[Array]$Results += $LineItem
}
$Results|export-csv c:\temp\output.csv -notype