Powershell script for getting AD Group Membership for usernames - powershell

I want to write script for getting AD Group Membership that is beginning with SSL_VPN for usernames listed in a CSV.
I have tried so far :
Import-Csv C:\Users.csv |
ForEach-Object -pv user { Get-AdUser -filter "displayname -eq '$($_.username)'"} |
Get-ADprincipalGroupMembership |
Select-Object #{ n = 'samaccountname'; e = { $user.samaccountname } }, name |
Export-csv -path C:\UserPermiss.csv -NoTypeInformation

Getting users by their DisplayName property is not the safest thing to do. It would be so much better if your CSV file has other, more unique properties to go by, like SamAccountName, UserPrincipalName, DistinguishedName or EmailAddress..
Anyway, in your loop, you should check if a user with that name can be found and only if so, get the group membership.
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName
if ($user) {
Get-ADprincipalGroupMembership -Identity $user.DistinguishedName |
Where-Object { $_.name -like 'SSL_VPN*' } |
Select-Object #{ Name = 'SamAccountName'; Expression = { $user.SamAccountName } },
#{ Name = 'Group'; Expression = { $_.name }}
}
else {
Write-Warning "User '$($_.username)' not found"
# if you want this message to also appear in your output CSV, do something like this:
[PsCustomObject]#{
'SamAccountName' = "User '$($_.username)' not found"
'Group' = ''
}
}
} | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
If you want to see a warning message when the user is not a member of the SSL_VPN group, you can do:
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName
if ($user) {
$group = Get-ADprincipalGroupMembership -Identity $user.DistinguishedName |
Where-Object { $_.name -like 'SSL_VPN*' }
if ($group) {
[PsCustomObject]#{
'SamAccountName' = $user.SamAccountName
'Group' = $group.name
}
}
else {
Write-Warning "User '$($_.username)' is not a member of ssl_vpn group"
}
}
else {
Write-Warning "User '$($_.username)' not found"
}
} | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation

You can use something like this(frist line of csv must be samaccountname):
$users=Import-Csv D:\adusers.CSV
foreach($user in $users){
$groupname=Get-ADPrincipalGroupMembership -Identity $user.samaccountname |where {$_.name -like "SSL_VPN*"}|select -ExpandProperty name
if($groupname -ne $null){
foreach($group in $groupname){
[string]$data=($user|select -ExpandProperty samaccountname)+';'+$group
$data|Out-File -FilePath d:\stack.csv -Encoding utf8 -Append
}
}
}

Related

Using a .txt file to find ManagedBy and ManagedBy Email within an AD Group

I'm having issues trying to have my script read and apply the AD groups with my script. Right now, it's just posting what's in my script, but I would like to have the script read what's in my .txt file and use it with the rest of my script.
$filePath = "C:\Users\UserName\Downloads\ADGroupList.txt"
Get-Content -Path $filePath
Get-ADGroup -filter {Name -like "$filePath" } -Properties managedBy |
ForEach-Object {
$managedBy = $_.managedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_; } |
Select-Object #{n='Group Name';e={$_.Name}}, #{n='Managed By Name';e={$managerName}}, #{n='Managed By Email';e={$managerEmail}}
Export-Csv -Path "C:\Users\UserName\Documents\ADGroupManagerList.csv"
The easiest way is to loop over the group names you have in the ADGroupList.txt file (assuming this is a list of group names, each on a separate line)
$filePath = "C:\Users\UserName\Downloads\ADGroupList.txt"
# just loop over the group names you have in the text file and capture the output
$result = Get-Content -Path $filePath | ForEach-Object {
$group = Get-ADGroup -Filter "Name -like '$_'" -Properties managedBy
# create an object pre filled in when no manager was found
$obj = [PsCustomObject]#{
'Group Name' = $group.Name
'Managed By Name' = 'N/A'
'Managed By Email' = 'N/A'
}
# test if the ManagedBy is populated
if (-not [string]::IsNullOrWhiteSpace($group.ManagedBy)) {
# try to use the DN in property ManagedBy to find the manager
try {
$manager = Get-ADUser -Identity $group.ManagedBy -Properties EmailAddress -ErrorAction Stop
$obj.'Managed By Name' = $manager.Name
$obj.'Managed By Email' = $manager.EmailAddress
}
catch {
Write-Warning "No user found for '$($group.ManagedBy)'.. Please check AD."
}
}
# output the object so it gets collected in variable $result
$obj
}
# write the file
$result | Export-Csv -Path "C:\Users\UserName\Documents\ADGroupManagerList.csv" -NoTypeInformation
For workaround you can use this powershell script to get the mangedBy of groups.
Get-ADGroup -filter * -Properties managedBy |
ForEach-Object {
$managedBy = $_.managedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_; } |
Select-Object #{n='Group Name';e={$_.Name}}, #{n='Managed By Name';e={$managerName}}, #{n='Managed By Email';e={$managerEmail}}

Updating CSV from AD properties without #{} in results

I have a script I am using to update a CSV file from my AD but it is currently outputting the results with #{} in the output CSV. So when I want to output the city it outputs #{city=toronto} instead of just toronto:
$USERS = Import-Csv "C:CSV import.csv"
$newCSV =ForEach ($User in $USERS) {
$Name = $User.name
[pscustomobject]#{
id = $user.id
name = $user.nameaddress1 = (Get-ADuser -Filter "name -like '$Name'" -properties StreetAddress | Select-Object StreetAddress)
address2 = (Get-ADUser -Filter "name -like '$Name'" -properties Office | Select-Object Office)
city = (Get-ADUser -Filter "name -like '$User.Name'" -properties City | Select-Object city)
}
}
$newCSV |export-csv "C:\CSVExport.csv" -NoTypeInformation
You're over complicating it, you can query the AD User once and then construct your export object with Select-Object:
Import-Csv "C:CSV import.csv" | ForEach-Object {
$Id = $_.Id
try {
Get-ADuser $_.Name -Properties StreetAddress, Office, City |
Select-Object #{N='Id'; E={ $Id }}, Name, StreetAddress, Office, City
}
catch { Write-Warning $_.Exception.Message }
} | Export-csv "C:\CSVExport.csv" -NoTypeInformation

Exporting Multiple AD User's membership via powershell

I want to know which group they have membership for. But I want to export samaccountname , displayname ,employeeid like below.
script :
$userlist = Get-Content 'C:\your\userlist.txt'
Get-ADUser -Filter '*' -Properties memberof | Where-Object {
$userlist -contains $_.SamAccountName
} | ForEach-Object {
$username = $_
$groups = $_ | Select-Object -Expand memberof |
ForEach-Object { (Get-ADGroup $_).Name }
"{0}: {1}" -f $username, ($groups -join ', ')
} | Out-File 'c:\temp\ss.csv'
My output :
CN=John T,DC=contoso,DC=local: IT_mail_group , IT_mail_group2
My desired output :
displayname;samaccountname;Staff ID;membership
John T ;johnt;1234; IT_mail_group , IT_mail_group2
Create 1 object per user, then export using Export-Csv:
Get-ADUser -Filter '*' -Properties memberof,employeeid,displayname | Where-Object {
$userlist -contains $_.SamAccountName
} | ForEach-Object {
[pscustomobject]#{
DisplayName = $_.DisplayName
SAMAccountName = $_.SAMAccountName
EmployeeID = $_.EmployeeID
Memberships = ($_.memberof |ForEach-Object { (Get-ADGroup $_).Name }) -join ', '
}
} | Export-Csv -Delimiter ';' -Path 'c:\temp\ss.csv' -NoTypeInformation

If user belongs to this group, show this, if not, show this

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

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 ", "}}