Export csv of groups that are not members of some groups - powershell

Im exporting some users and groups that "are not member of". But Im having troubles with groups, I did it with users but I don't know how to do the same with group.
In this example I export users that are not members of that group.
$groups = 'GG_LCS_UsersType4', 'GG_LCS_UsersType3', 'GG_LCS_UsersType2', 'GG_LCS_SpecialUsers'
$whereFilter = $groups | Foreach-Object {
$g = (Get-ADGroup -server $domain $_).DistinguishedName
"{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADUser -server $Domain -filter {objectclass -eq "user"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
Export-Csv "${Domain}_Users_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append
So I want the groups too. Could you help me please?
Thank you!

Technically, you should be able to just add a Get-ADGroup command at the end of the posted code and then export the desired data.
$FilteredGroups = (Get-ADGroup -Server $Domain -Filter * -Properties MemberOf).where($whereFilter)
$FilteredGroups | Select-Object SamAccountName |
Export-Csv "groups.csv" -NoTypeInformation -Encoding UTF8 -Append

Related

How to check if disabled samaccountnames are contained/part of an enabled samaccountname in AD (e.g. the disabled user has -adm or -tst account?_

I am able to export the disabled users, but then from that .csv I want to check if they have active accounts in AD, containing their samaccount name + -adm or -tst. The script runs but the second export is blank.
$users = import-csv C:\Users\....csv
$OU = 'OU=Disabled users ...'
Get-ADUser -Property Enabled -filter * -SearchBase $OU | Where {$_.Enabled -like "False"} | Select #{Name="samaccountname";Expression={$_.SamAccountName}} | Export-Csv C:\Users\... -notypeinformation -encoding UTF8
$data = foreach($line in $users){
$user = $line.samaccountname
Get-ADUser -Filter {(samaccountname -like $user) -and (samaccountname -like "*-adm") -and (samaccountname -like "*-tst")} -Properties Enabled | Where {$_.Enabled -like "True"} | select #{Name="SAPID";Expression={$_.samaccountname}}
} $data | export-csv C:\Users\... -notypeinformation -encoding UTF8
If I understand correctly, you're looking to find all those Enabled Accounts ending in -adm OR -tst AND containing the SamAccountName of ANY disabled user found in $OU.
If my assumption is correct, one way to approach the problem is to first query all the Disabled users in $OU and have them in memory (Note that there is no need to export them to CSV and then import them back again - see inline comments).
Once we have the list of Disabled users, we can loop over them to construct an LDAP Filter which will be used to query all users at once, and lastly export to CSV if any user was found.
$users = Import-Csv C:\Users\....csv
$OU = 'OU=Disabled users ...'
# Hold disabled Users under `$OU` in memory, no reason to import the data from CSV
$disabledUsers = Get-ADUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=2)" -SearchBase $OU |
Select-Object SamAccountName
# Export Disabled Users
$disabledUsers | Export-Csv C:\Users\... -NoTypeInformation -Encoding utf8
# Construct an LDAP Filter to query al users at once
$filters = foreach($user in $disabledUsers) {
'(samAccountName=*{0}*-adm)(samAccountName=*{0}*-tst)' -f $user.SamAccountName
}
$ldapFilter = "(&(!userAccountControl:1.2.840.113556.1.4.803:=2)(|$(-join $filters)))"
# Query the users
$enabledUsers = Get-ADUser -LDAPFilter $ldapFilter
# Check if any user could be found
if(-not $enabledUsers) {
'No Enabled -adm or -tst Account Could be found...'
}
else {
$enabledUsers | Select-Object #{ N = "SAPID"; E = { $_.SamAccountName} } |
Export-Csv C:\Users\... -NoTypeInformation -Encoding utf8
}
This is an example of how the filter would look like, having user0 and user1 as example SamAccountName:
(&
(!userAccountControl:1.2.840.113556.1.4.803:=2)
(|
(samAccountName=*user0*-adm)
(samAccountName=*user0*-tst)
(samAccountName=*user1*-adm)
(samAccountName=*user1*-tst)
)
)

Powershell: List with ADusers - need groups the users are memberof

I have a list of users (their CN), and I want a list of the groups they are member of.
I already have a code which almost does the trick, but it shows as follows:
User1 - group1;group2
User2 - group1;group2;group3 etc...
Also, groups are shown as distinguished name (with container etc), so very long. I only want the name.
I want to show it as follows:
User1 - group1
User1 - group2
User2 - group1, etc
The code that shows the groups the users are member of, but not in the visual way i like is below:
Import-Csv -Path .\Input_CN.csv |
ForEach-Object {
$User = Get-ADUser -filter "CN -eq '$($_.CN)'" -properties memberof
[PSCustomObject]#{
SourceCN = $_.CN
MemberOf = $User.MemberOf -join ";"
}
} | Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
.\Output.csv
I have some other code that list the groups how I want, but I am unable to list it per user. And unable to combine it with the above code.
get-aduser -filter {cn -eq "Testuser"} -properties memberof |
Select -ExpandProperty memberof |
ForEach-Object{Get-ADGroup $_} |
Select -ExpandProperty Name
Thanks in advance :)
You could combine both code pieces like this:
Import-Csv -Path .\Input_CN.csv |
ForEach-Object {
$user = Get-ADUser -Filter "CN -eq '$($_.CN)'" -Properties MemberOf, CN -ErrorAction SilentlyContinue
foreach($group in $user.MemberOf) {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = (Get-ADGroup -Identity $group).Name
}
}
} | Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
Edit
Although I have never seen an AD user to have no group membership at all (should have at least the default Domain Users in the MemberOf property), You commented that you would like to have a test for that aswell.
Import-Csv -Path .\Input_CN.csv |
ForEach-Object {
$user = Get-ADUser -Filter "CN -eq '$($_.CN)'" -Properties MemberOf, CN -ErrorAction SilentlyContinue
if (!$user) {
Write-Warning "No user found with CN '$($_.CN)'"
# skip this one and resume with the next CN in the list
continue
}
$groups = $user.MemberOf
if (!$groups -or $groups.Count -eq 0) {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = 'No Groups'
}
}
else {
foreach($group in $groups) {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = (Get-ADGroup -Identity $group).Name
}
}
}
} | Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
This is a bit clunky, but you can use nested loops:
Import-Csv -Path .\Input_CN.csv | ForEach-Object {
$user = Get-ADUser -filter "CN -eq '$($_.CN)'" -properties cn, memberof
$user | ForEach-Object {
$_.MemberOf |
ForEach-Object {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = $_.split('[=,]')[1]
}
}
}
} | Where-Object {$null -ne $_.MemberOf} |
Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
UPDATE: Updated to show only the 'CN' part of the group name and to filter any users who are not a member of any group.
All in one line could be
Get-ADUser -filter {Enabled -eq $True} -Properties Name, Created | Select-Object Name, Created, #{Name="Groups";Expression={Get-ADPrincipalGroupMembership -Identity $_.SamAccountName | Where-Object {$_.GroupCategory -Eq 'Security'} | Join-String -Property Name -Separator ", "}}

Find computers that are not members of a specific GG group

I use a script to export users that are not in specific GG groups in active directory but I want to do the same with computers.
This is the example that works with users:
$groups = 'GG_LCS_UsersType4', 'GG_LCS_UsersType3', 'GG_LCS_UsersType2', 'GG_LCS_SpecialUsers'
$whereFilter = $groups | Foreach-Object {
$g = (Get-ADGroup -server $domain $_).DistinguishedName
"{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADUser -server $Domain -filter {objectclass -eq "user"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
Export-Csv "${Domain}_Users_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append
And I tried this in order to do the same with computers, but this doesn't work:
$groups = 'GG_LCS_ComputersType2', 'GG_LCS_ComputersType3', 'GG_LCS_ComputersType4'
$whereFilter = $groups | Foreach-Object {
$g = (Get-ADGroup -server $domain $_).DistinguishedName
"{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADComputer -server $Domain -filter {objectclass -eq "computer"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
Export-Csv "${Domain}_Computers_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append
Could you help me? Thanks!
Try adding the -SearchBase
$AD = Get-ADComputer -Filter * -Properties $properties -SearchBase "DC=subdomain,DC=domain,DC=com" -Server $server
$AD | Select-Object * | Export-Csv -NoTypeInformation $filePath -Encoding UTF8

Powershell Script to Export All Groups and Members Assigned for a given OU to a CSV

I am trying to export all groups and the members assigned (if any) for a given OU. How do I include groups with no members?
Get-ADGroup -Properties * -Filter * -SearchBase "OU=BI-Security,OU=BH-Security Groups,DC=bh,DC=intra" | Foreach {
$Group = $_
Get-ADGroupMember -Id $Group | `
select #{Expression={$Group.Name};Label="Group Name"},Name | `
Export-CSV C:\Scripts\BIGroups.CSV -NoTypeInformation -append
}
Thanks in advance.
Call Get-ADGroupMember inside a calculated property with Select-Object:
$groups = Get-ADGroup -Filter * -SearchBase 'OU=BI-Security,OU=BH-Security Groups,DC=bh,DC=intra'
$groups |Select-Object #{Expression={$_.Name};Label='Group Name'},#{Expression={#(Get-ADGroupMember -Identity $_|Select -Expand Name) -join ';'};Label='Name'} | Export-CSV C:\Scripts\BIGroups.CSV -NoTypeInformation -append

Powershell Import-CSV and Foreach-Object, excluding with the CSV header

I'm trying to get the SAMAccountNames of one domain and compare them with their equals from another domain.
To get all users of dc1 I use:
Get-ADUser -Filter * -SearchBase $SearchBase | Select-Object SamAccountName |
Export-Csv -path $exports -encoding "unicode" -notype
and then I import the csv again and try to compare them for any differences
$readthat = Import-CSV $exports -Header SamAccountName | ForEach-Object {
$user1 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes
$user2 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes -Server $dc2
$modified = #{}
$attributes | Where-Object { $user1.$_ -ne $user2.$_ } | ForEach-Object {
$modified[$_] = $user2.$_
}
}
All that works great, except that it's also trying to find the SamAccountName which of course genereates an error because the SamAccountName = SamAccountName doesn't exit.
Any hints on how to avoid this or do you guys have a more elegant solution?
the .csv looks like this:
"SamAccountName"
"foo"
"bar"
Don't use the -Header SamAccountName option on your import-csv should help immensely. The -Header option is for when the CSV file you are importing doesn't have a header. The Export-CSV cmdlet puts the header in there for you, so you don't have to.