0

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

WouterG
  • 1
  • 1
  • Can you please add the contents of the `$users#`, `$userslist`, and `$members` variables to the body of your question? The first few lines should suffice. – Andrew Ryan Davis Sep 23 '20 at 20:30
  • I don't have $users, only $user and that one is empty $userslist = WGoossensTest wgoossenstest2 $members = username1, username2 (I prefer not to include real usernames, but the wgoossenstest accounts are not in this group, so not in this array) – WouterG Sep 23 '20 at 20:45
  • 1
    Feel free to obfuscate the usernames to anything you want, "testUser1, testUser2, testUser3". The important thing is to include the contents in the format they appear in the PowerShell variable you're working with. And please include them in the body of the question, rather than a comment, for formatting reasons. – Andrew Ryan Davis Sep 23 '20 at 20:50

1 Answers1

1

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.

Doug Maurer
  • 8,090
  • 3
  • 12
  • 13
  • Hi Doug, thank you very much for your answer. I tried your second script and it seems to work fine! Only when I have only 1 user it gives an error: – WouterG Sep 24 '20 at 09:46
  • Method invocation failed because [Selected.Microsoft.ActiveDirectory.Management.ADUser] does not contain a method named 'where'. At \\dtc-data1\Personal\WGoossens\Scripts\Remove_Outlookuserpref_files_and_add_to_FSLogix_group.ps1:20 char:1 + $notmembersof,$membersof = $userslist.where({$_.samaccountname -notin $members}, ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (where:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound – WouterG Sep 24 '20 at 09:46
  • But it does seem to work with more users. Could that be because of the split? – WouterG Sep 24 '20 at 09:46
  • Yes if you expect nothing in the list then we should do a check before continuing on. I can update the answer later. That error means userlist was empty and we tried to run a where method against an empty list – Doug Maurer Sep 24 '20 at 12:57
  • okay, yes that one person is already member of that group, so the $notmembersof should be empty, but the $membersof not. But when I check, both of the variables are empty. But when I do $userslist, it shows samAccountname and beneath that that 1 person's samAccountname. If you can check later on how to build that in, it would be great! thanks again! – WouterG Sep 24 '20 at 13:02
  • No userlist is empty. – Doug Maurer Sep 24 '20 at 13:03
  • Hi Doug, I tried your test code, but than I get the same error I got before: Method invocation failed because [System.String] does not contain a method named 'where'. At line:3 char:1 + $match,$nomatch = $userlist.where({$_ -in $members},'split') – WouterG Sep 25 '20 at 08:45