Powershell loop deal with multiple AD users in output - loops

I have constructed below to show an certain active directory users details and all their groups.
This works ok if only one user is returned howver if multiple users are returned I get an error with this section: "Get-ADPrincipalGroupMembership $user.samaccountname | select name"
I've looked in the direction of for loops but haven't yet found a solution
I need each user found displayed with their groups.
I plan to use this script to quickly gather info to troubleshoot user issues.
Thanks for reading
add-pssnapin quest.activeroles.admanagement
import-module activedirectory
clear-host
$name = read-host 'Whats the name ?'
$user = Get-qAduser $name -properties *
$user | select name,SamAccountName,AccountIsLockedOut,PasswordStatus,PasswordLastSet,PasswordExpires,email,ParentContainerDN,CreationDate | format-list
Get-ADPrincipalGroupMembership $user.samaccountname | select name
cmd /c pause | Out-Null

Just assume you're getting a list back and then use a foreach to iterate over the list:
add-pssnapin quest.activeroles.admanagement
import-module activedirectory
clear-host
$name = read-host 'Whats the name ?'
$users = Get-qAduser $name -properties *
foreach ($user in $users) {
$user | select name,SamAccountName,AccountIsLockedOut,PasswordStatus,PasswordLastSet,PasswordExpires,email,ParentContainerDN,CreationDate | format-list
Get-ADPrincipalGroupMembership $user.samaccountname | select name
}

Related

Change multiple group's managed by to user's manager by powershell

I'm very new in powershell. I'm trying to create a script to disable the AD account and do multiple tasks in it.
I'm stuck in the part where i want to assign all the Distribution lists and Security Groups managed by the user to his manager. Below is the script, any help would be appreciated.
$SamAccountName = Read-Host "Enter the username"
$ManagedObjects = Get-ADUser $SamAccountName -Properties managedObjects |select -ExpandProperty managedObjects
$Manager = Get-ADUser $SamAccountName -Properties manager | Select -ExpandProperty Manager
$ManagedObjects | ForEach-Object {
Set-ADGroup -Identity $_.Group -ManagedBy ($Manager.DistinguishedName)
}
I have tested in my environment.
You can use the below PowerShell script to change multiple group's managed by to user's manager :
$SamAccountName = Read-Host "Enter the username"
$ManagedObjects = Get-ADUser $SamAccountName -Properties managedobjects | select -ExpandProperty managedObjects
$Manager = Get-ADUser "labadmin" -Properties manager | Select -ExpandProperty Manager
foreach ($group in $ManagedObjects)
{
Set-ADGroup -Identity $group -ManagedBy $Manager
}

Get-ADUser return a single account from all OU's and Sub OU's

I have the following sample OU structure in my Active Directory server
I have user accounts in the "users" OU in each of OU1, OU2 and so on.
The user accounts have a static prefix e.g. OU1 will have user accounts like OU1user1,OU1user2,OU1user3 and so on. Similarly OU2 and OU3 will have use accounts like OU2user2,OU2user2,OU2user3 & OU3user1,OU3user2,OU3user3
Now what I want?
I want only a single user (it can be any user) from all of the OU's under the RootOU. Currently i am using the following command and its returning all the users inside the RootOU's sub-OU.
$ou = "OU=RootOU,DC=mydomain,DC=com"
$myUsers = Get-ADUser -Filter * -SearchBase $ou -SearchScope 2
You can probably do something like
$myUsers = Get-ADOrganizationalUnit -Filter "Name -like '*users*'" -SearchBase $ou -SearchScope 2 | ForEach-Object {
Get-ADUser -Filter * | Select-Object -First 1
}

How to add users to AD group and delete some specific user files based on first letters username with Powershell

hope someone could help, I'm unfortunatelly not a Powershell expert
This is what I want:
look up users in the AD within specific OUs, based on first letter(s) of username.
Validate if they are member of a AD group, and if not;
delete some specific profile files of the user AND
add the user to that specific group.
Some part of the code I tried:
Import-Module ActiveDirectory
# OUs needed to be searched for users
$OU1 = 'name of first OU'
$OU2 = 'name of 2nd OU'
$OU3 = 'name of 3rd OU'
# AD group where users needs to be added
$Group = 'name of group'
# Ask for 1st letter of username
$usernameletter = Read-Host -Prompt 'First letter(s) username'
# Create an array with corresponding users
$userslist= #()
$users1 = Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $OU1 | select -ExpandProperty samAccountName
$users2 = Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $OU2 | select -ExpandProperty samAccountName
$users3 = Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $OU3 | select -ExpandProperty samAccountName
$userslist += $users1,$users2,$users3
# check membership of group
$members = Get-ADGroupMember -Identity $Group -Recursive | Select -ExpandProperty sAMAccountName
# Delete userpref files of user when user is not member of the -name of group-
foreach ($user in $userslist)
{
If ($members -contains $user)
{
Write-host "$user exists in group, so userpref files won't be deleted"
}
Else
{
#if users doesn't exist in AD Group - delete userpref files of user
Write-host "$user doesn't exist in group, deleting userpref files of user"
Remove-Item -Path E:\users\$user\pwrmenu\UserPref\{F5BE2CE1-BF67-44E2-B5B3-5E081344A70E}* -Force
}
}
# check if user is part of the group. if not, add it to the group
foreach ($user in $userslist)
{
If ($members -contains $user)
{
Write-host "$user exists in group, so user won't be added to group $group"
}
Else
{
#if users doesn't exist in AD Group - add them to AD Group
Write-host "$user doesn't exist in group, adding user to group $group"
Add-ADGroupMember $Group -Members $userslist
}
}
#end of script
for some reason the $userslist array is filled, but the foreach loop $user in $userslist doesn't work, $user is not filled in and it get errors like
Remove-Item : Cannot find path 'E:\users\pwrmenu\UserPref' because it does not exist.
Add-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null, empty, or an element of the argument collection contains a null value.
Hope that someone could help me! thanks!
Edit
#Andrew Ryan Davis,
sorry, not very familiar with this website yet
contents of $userslist:
PS C:\Users\serverw> $userslist
WGoossensTest
wgoossenstest2
contents of $members:
PS C:\Users\serverw> $members
username1
username2
username3
etc
Not sure why you wouldn't have anything populated in user. I do see you have quite a bit of duplicated code as well as several chances for optimization. If you keep the users as an object with a samaccountname property, you can speed up your where clause by not invoking a scriptblock.
$userslist | where samaccountname -notin $members
or
$userslist | where $members -notcontains samaccountname
You also check each user against the list of group members twice. Check out the optimized version below.
Import-Module ActiveDirectory
# OUs needed to be searched for users
$OUs = 'name of first OU','name of 2nd OU','name of 3rd OU'
# AD group where users needs to be added
$Group = 'name of group'
# Ask for 1st letter of username
$usernameletter = Read-Host -Prompt 'First letter(s) username'
# Create an array with corresponding users
$userslist = $ous | foreach {
Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $_ | select samaccountname
}
# Get member list of group
$members = Get-ADGroupMember -Identity $Group -Recursive | Select -ExpandProperty sAMAccountName
# Delete userpref files of user when user is not member of the -name of group- and then add to the group
foreach($user in $userslist | where samaccountname -notin $members | select -ExpandProperty sAMAccountName)
{
Write-host "$user doesn't exist in group, deleting userpref files of user"
Remove-Item -Path E:\users\$user\pwrmenu\UserPref\{F5BE2CE1-BF67-44E2-B5B3-5E081344A70E}* -WhatIf
Write-host "$user doesn't exist in group, adding user to group $group"
Add-ADGroupMember $Group -Members $user -whatif
}
#end of script
This does not provide feedback of users in the group. If you really want to see that then you can split them up and run each separately.
Import-Module ActiveDirectory
# OUs needed to be searched for users
$OUs = 'name of first OU','name of 2nd OU','name of 3rd OU'
# AD group where users needs to be added
$Group = 'name of group'
# Ask for 1st letter of username
$usernameletter = Read-Host -Prompt 'First letter(s) username'
# Create an array with corresponding users
$userslist = $ous | foreach {
Get-ADUser -Filter "SamAccountName -like '$usernameletter*'" -SearchBase $_ | select samaccountname
}
# Get member list of group
$members = Get-ADGroupMember -Identity $Group -Recursive | Select -ExpandProperty sAMAccountName
$notmembersof,$membersof = $userslist.where({$_.samaccountname -notin $members},'split')
# Delete userpref files of user when user is not member of the -name of group- and then add to the group
foreach($user in $notmembersof.sAMAccountName)
{
Write-host "$user doesn't exist in group, deleting userpref files of user"
Remove-Item -Path E:\users\$user\pwrmenu\UserPref\{F5BE2CE1-BF67-44E2-B5B3-5E081344A70E}* -WhatIf
Write-host "$user doesn't exist in group, adding user to group $group"
Add-ADGroupMember $Group -Members $user -whatif
}
foreach($user in $membersof.sAMAccountName)
{
Write-host "$user exists in group, so userpref files won't be deleted"
Write-host "$user exists in group, so user won't be added to group $group"
}
#end of script
Another issue you may have already ran into is your Add-ADGroupMember targets the entire $userslist instead of each $user. I added -WhatIf so you can triple check what's going to happen before completing.
Edit
If $userlist may be empty then we should do a check, something like.
if($null -eq $userlist){write-host "userlist is empty";break}
The error in your comment shows that $userlist was empty, try these tests.
$members = 'test'
$userlist = 'test'
$match,$nomatch = $userlist.where({$_ -in $members},'split')
$members = 'test1'
$userlist = 'test'
$match,$nomatch = $userlist.where({$_ -in $members},'split')
Neither will error and in the first $match will be populated and $nomatch will be empty. In the second the opposite will be true. In neither case will it error like the one you saw.

How to use dsquery to list the members of a distribution list?

I have this command to find a distribution list object
dsquery * -filter "(&(cn=*group))"
but now how can I find the users from that, I want to loop through and get their names and email addresses from it.
Thanks
Now that you have the group name, you can use PowerShell to iterate through the group and extract the information you need:
Import-Module ActiveDirectory
$group = read-host "Please Enter Group Name: "
$members = Get-ADGroupMember -Identity $group -Recursive
ForEach ($member in $members) {
$memberType = $member.objectClass
If ($memberType -eq 'user') {
Get-ADUser -Filter "name -like '*$member'" -Properties cn,mail | Out-File c:\temp\Group_Members.csv -append
}
}
The code above will prompt for the group name and export the list of members, including where there is a nested group into the a file called Group_Members.csv in c:\temp.
You will need to ensure that:
Script execution is enabled in Powershell;
That RSAT is installed on the device that the script is executed from;
That the script is executed with administrator privileges.

Get users (sammacountname) in ad group, save them in csv, display all of the groups of these users

Im trying to write a script wchich will:
take members of the specific AD group
save it to a csv file
print user of the group and all of the groups user is the member of
I want the print results to be in one line
My code looks like this
$group = Read-Host -Prompt 'Enter the group name'
Get-ADGroupMember -identity $group -Recursive | % { get-aduser $_} | select SamAccountName | export-csv userzy.csv
$file = import-csv userzy.csv
ForEach ($user In $file)
{
$user
(Get-ADUser $user –Properties MemberOf | Select-Object MemberOf).MemberOf
}
Im stuck when it comes to looping through csv in order to display users and their groups
1. I dont know how to make in one line
2. When im running Get-ADuser in my loop im getting an error:
Get-ADUser : Cannot bind parameter 'Identity'. Cannot convert value "#{SamAccountName=mczechow}" to type "Microsoft.ActiveDi
rectory.Management.ADUser". Error: "Cannot convert the "#{SamAccountName=mczechow}" value of type "CSV:Selected.Microsoft.Ac
tiveDirectory.Management.ADUser" to type "Microsoft.ActiveDirectory.Management.ADUser"."
At C:\Users\mgiedyk\Desktop\skrypty\groupmembers.ps1:16 char:13
+ Get-ADUser $user -Properties MemberOf
+ ~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Thank you in advance for your help.
Just replace
Get-ADUser $user –Properties MemberOf ...
to
Get-ADUser -Filter{SamAccountName -like $user} –Properties MemberOf ...

Resources