Check if user exists in group - powershell

I cant get this script to give the right output, I want to check if a user (from the Users.csv) exists in a group (there is one group in each domain, this is a multi domain environment).
I think the problem lies in the second foreach.
Right now the output is the right numbers of lines for each domain, but they all say :
aa#aa.aa bb#bb.bb does not exists in the group PSO_StdPasswordPolicyWithNoAccountLockout
Where it should say:
aa#aa.aa does not exists in the group
PSO_StdPasswordPolicyWithNoAccountLockout
bb#bb.bb does not exists in the group
PSO_StdPasswordPolicyWithNoAccountLockout
Users.csv contains EmailAddress, DisplayName, objectGUID
Clear-Host
$user = Import-Csv ".\Users.csv"
$group = "PSO_StdPasswordPolicyWithNoAccountLockout"
$domains = (Get-ADForest).domains
foreach ($domain in $domains) {
Write-Host ="********** - $domain - **********" -ForegroundColor Yellow
$members = Get-ADGroupMember -Identity $group -Server $domain | Select-Object objectGUID
$exportMembers = $members | Export-Csv .\RemoveUsersTemp\$domain.csv -NoTypeInformation
$importFile = ".\RemoveUsersTemp\$domain.csv"
$amembers = import-csv $importFile | Select-Object objectGUID
foreach ($amember in $amembers) {
If ($amembers.objectGUID -contains $user.objectGUID) {
Write-Host $user.EmailAddress"exists in the group $group " -ForegroundColor Green
}
Else {
Write-Host $user.EmailAddress"does not exists in the group $group" -ForegroundColor Red
}
}
}

This is because you use $user in the second loop, but you're not looping $user, so you're referring the whole $user array, which has the content of users.csv.

Related

Delete the ":" character from results

I'm trying to list only unique HomeDrive for all users in a Universal Security group and remove nested groups errors.
Thanks for your help.
Denis
I've tried .TrimEnd(':'), can't seem to figure out where to put it
$Group = "Universal Security group"
$HomeDrive = Get-ADGroupMember $Group | `
ForEach-Object {
$UserName = $_.Name
Try {
#$ErrorActionPreference = "Stop"
Get-ADUser $UserName -Properties HomeDrive | Select HomeDrive
}
Catch {
Write-Host "Found a nested Group."
}
} | Sort-Object -Property 'HomeDrive' -Unique | Format-Table -HideTableHeaders | Out-String
Write-Host "$HomeDrive" -BackgroundColor DarkRed
The script does work but some users have their homedrives listed as only F while most are listed as F:. Basically making a lot of double entries and I do want the output to be only F. Also it generates 7 spaces after the :, That's why I have the background color.
Something like this:
$group = "Universal Security group"
$homeDrives = Get-ADGroupMember $Group |
ForEach-Object {
if ($_.ObjectClass -eq "User")
{
$user = Get-ADUser $_.Name -Properties "HomeDrive"
$homeDrive = $user.HomeDrive.Trim().TrimEnd(":")
return $homeDrive
}
} | Sort-Object -Unique
foreach ($homeDrive in $homeDrives)
{
Write-Host "Found home drive: $homeDrive" -BackgroundColor DarkRed
}

Filtering AD Group by User Properties ; Returning improperly

Disclaimer: I am not good with powershell, this in mainly butchered code. I apologize if this is done poorly or is a stupid question.
I am trying to filter the ACTIVE users in my company by their company (ET) and whether or not they are in a certain group.
So the filter for ACTIVE users in the company "ET" is working properly, the output of this script gives me every active users with that parameter; it does not filter it further down into only users in a certain group.
$users = Get-ADUser -filter {(Enabled -eq $True) -and (Company -eq "ET")}
-SearchBase 'DC=CSOKI,DC=Local' |select -exp samaccountname
$group = "O365-E3-Full"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -
ExpandProperty samaccountname
ForEach ($user in $users) {
If ($members -contains $user) {
Write-output $(name) | out-file ".\TEST.txt"
} Else {
Write-Host "$user does not exist in the group"
}}
Expected:
Output ACTIVE users in company ET that are in group O365-E3-FULL and write-host users that are not(unnecessary, I just want the filter).
Actual:
Write-hosts every ACTIVE user in company ET and ignores the group filter.
In getting your list of users you are collecting the account name for the users with:
| Select -exp samaccountname
Then in getting group members you are getting the Name with:
| Select -ExpandProperty Name
You need to be selecting SamAccountName in both of your Gets
Sorry, pretty quick knock together
# Create empty array
$answer = New-Object System.Collections.ArrayList
# If is in group then add to array
If ($members -contains $user) {
$answer.Add($user) > $null
} Else {
Write-Host $user "does not exist in the group"
}
# Output the array to the text file
Write-output $answer | out-file ".\TEST.txt"

Powershell import-csv

Creating a script that checks if a list of users from csv file are in a specific AD Group
Import-Module ActiveDirectory
$userscsv = Import-Csv C:\User-list.csv
$group = "testgroup"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
ForEach ($user in $userscsv) {
If ($members -contains $user) {
Write-Host "$user exists in the group"
} Else {
Write-Host "$user does not exists in the group"
}}​
In my csv file i have the names in A1 A2 A# etc I get this format bellow:
#{Johnny Walker=Alex Hood} does not exists in the group
I added
$userscsv = Import-Csv C:\User-list.csv | select -ExpandProperty User
It worked, if you guys have some feedback and tweaking, I'm all ears

PowerShell ConvertFrom-Csv

So Here is my code. Essentially this code will be used by a domain admin to run on our terminal server. I lists all of the currently logged in users, and check their individual group membership and then counts members. Easy Peasy.
99% of this works as expected but I am not a code guru by far. I'm having problems getting a proper list of names from Line 4 which uses quser. If I switch to using Line 5 as text the code works as expected.
I can't for the life of me get the output from line 4 into a format I can use in the rest of the code.
Import-Module ActiveDirectory
$calgary = 0
$edmonton = 0
$users = (quser) -replace '\s{2,}', ',' | ConvertFrom-Csv | Select-Object USERNAME
$usersold = "Thomas", "Scott", "jeremy"
$groups = 'Domain Admins'
foreach ($user in $users) {
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $user) {
$calgary = $calgary + 1
Write-Host "$user is a member of $group"
Write-Host "$group has $calgary logged in users"
} Else {
Write-Host "$user is not a member of $group"
}
}
}
$users.GetType() returns an Array of elements of type PSCustomObject, so this is an object with properties, rather than just a list of strings.
When you do ($user in $users) then each $user is an object with the USERNAME property. So you have two options:
Access the USERNAME in the loop
When you need the username inside the loop, use $user.USERNAME
Get a list of strings rather than objects
Replace line 4 with:
$users = $((quser) -replace '\s{2,}', ',' | ConvertFrom-Csv | Select-Object USERNAME).USERNAME
On line 4, try using:
$users = ((quser) -replace '\s{2,}', ',' | ConvertFrom-Csv | Select-Object USERNAME).username
I think a better way to get a list of logged on users is to use Get-CimInstance to gather the sessions, filter for LogonType 3 (remote logon), and then get the users associated with those logon IDs. Then, since it looks like you want to be able to check multiple groups, I would get the members for each group, and just note if each user is a member of each group. At the end I would output a table of all sessions, including which groups each user is a member of, and how many users each group has logged on.
$LoggedOn = gcim Win32_LoggedOnUser
$GroupNames = 'pkiadmins'
$Groups = #{}
$GroupNames | ForEach-Object { $Groups.Add($_,(Get-ADGroupMember -Identity $_ -Recursive | Select -Expand SamAccountName)) }
$Sessions = gcim Win32_LogonSession -PipelineVariable Session|?{$_.LogonType -eq 3}|%{
$SesUser = $LoggedOn|?{$_.Dependent.LogonId -eq $Session.LogonId}
$SessionOut = [PSCustomObject]#{
Domain = $SesUser.Antecedent.Domain
User = $SesUser.Antecedent.Name
}
ForEach($Group in $GroupNames){
Add-Member -InputObject $SessionOut -NotePropertyName $Group -NotePropertyValue ($SessionOut.User -in $Groups[$Group])
}
If($SessionOut.User -notmatch '\$$'){$SessionOut} #skip computer accounts
}
$Sessions|FT -Auto
ForEach($Group in $GroupNames){
"Group '{0}' has {1} logged in user(s)" -f $Group,([array]($Sessions|?{$_.$Group})).Count
}

PowerShell - Adding New User to Selection of AD Groups

I've created a form to create new AD Accounts. Part of the script determines which groups the new user will be added to based on their role (Doctor, Nurse, Admin or Other) which is captured in the following code in the form of a drop down pick box:
Write-Host "Based on this information" $FFN "has been added to the following Active Directory Groups:"
Write-Host
$ADGroup01 = Get-ADGroup "_XA_App_XenApp" |select -expandproperty name -first 1
Write-Host $ADGroup01
$ADGroup02 = Get-ADGroup "Web Proxy Users" |select -expandproperty name -first 1
Write-Host $ADGroup02
if($RadioButton1.Checked -eq $true)
{
$ADGroup03 = Get-ADGroup "allrot" |select -expandproperty name -first 1
Write-Host $ADGroup03
}
Else
{
$ADGroup03 = Get-ADGroup "alltpo" |select -expandproperty name -first 1
Write-Host $ADGroup03
}
if ($Role -eq "Doctor" -Or $Role -eq "Nurse")
{
$ADGroup04 = Get-ADGroup "PACS Web Access" |select -expandproperty name -first 1
Write-Host $ADGroup04
}
if ($Role -eq "Doctor")
{
$ADGroup05 = Get-ADGroup "CH-MFD" |select -expandproperty name -first 1
Write-Host $ADGroup05
$ADGroup06 = Get-ADGroup "ED-MFP" |select -expandproperty name -first 1
Write-Host $ADGroup06
$ADGroup07 = Get-ADGroup "SU-MFD" |select -expandproperty name -first 1
Write-Host $ADGroup07
}
Write-Host
Further on in the script this piece of code is called during the actual account creation process:
Add-ADPrincipalGroupMembership -Identity $UN -memberof $ADGroup01, $ADGroup02, $ADGroup03, $ADGroup04, $ADGroup05, $ADGroup06, $ADGroup07
The issue I'm facing is that if the user selects Nurse, Admin or Other I get the following error:
"Add-ADPrincipalGroupMembership : Cannot validate argument on parameter 'MemberO
f'. The argument is null, empty, or an element of the argument collection conta
ins a null value. Supply a collection that does not contain any null values and
then try the command again."
I know this is because there are no values being captured in the last $ADGroup[x] and short of creating a bunch of if statements to check if each $ADGroup contains data I'm wondering if there is a more elegant solution.
As always, thank you for taking the time review and happy to provide more information if required.
UPDATE - As per #Martin's advice I've implemented the following code into my script
$UN = "zooz"
$Role = "Nurse"
$Department = "Surgical"
If ($Role -eq "Doctor" -and $Department -eq "Surgical")
{
$ADGroups = #(
"PACS Web Access"
"CH-MFD"
"ED-MFP"
"SU-MFD"
)
}
If ($Role -eq "Nurse" -and $Department -eq "Surgical")
{
$ADGroups = #(
"_XA_App_XenApp"
"Web Proxy Users"
"allrot"
)
}
for ($i=0; $i -lt $ADGroups.length; $i++) {
Add-ADPrincipalGroupMembership -Identity $UN -memberof $adgroups[$i]
}
Make an object $adgroups and add your desired groups to it.
$adgroups = #()
At the end use a foreach Loop:
$adgroups | Add-ADPrincipalGroupMembership -Identity $UN or (weather or not the cmdlet likes pipelined Input)
$adgroups | % { Add-ADPrincipalGroupMembership -Identity $UN -memberof $_ }