Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Trouble with if else statement in script to add users to group

$
0
0

So I wrote this powershell script to add users to a distribution group and it's working fine, but we want a clean log to be able to see what was done. I'm trying to use an if else statement to differentiate between who's added an who isn't. However I can't seem to get that part to work. Currently the if statement is "if (($i.memberOf -match $group))" and it always executes the else statement. If I change it to "if (!($i.memberOf -match $group))" then it always executes the if statement. Was wondering if anyone had any advice to help point me in the right direction, the whole code is below.

Thanks!

Import-Module ActiveDirectory
$group = "Test Group"
$user = (Get-ADUser -Filter * -SearchBase "ou=Test Users,dc=test,dc=org")
$OutputFileLocation = "C:\output.log"
Function Add-ADUserToGroup
{
Start-Transcript -path $OutputFileLocation -append    
foreach($i in $user)
{
    if (!($i.memberOf -match $group))    
    {
        Write-Output "$i is already a member of $group" | out-host        
    }
    else
    {        
        Write-Output "$i had been added to $group" | out-host
        Add-ADGroupMember -Identity $group -Member $i
    }
}
Stop-Transcript
}
Add-ADUserToGroup

Viewing all articles
Browse latest Browse all 21975

Trending Articles