Check to Stop Error

Hi all,

I am very new to PowerShell, Super new infact. I have managed to coble together this script from bits and pieces around here ( Hundred thanks to those who supplied the bits ) but now Im stuck. What it does is read Security groups from a csv. A source column and a target column. and then writes the users from the source to target. It does that ok and even writes a nice error log for someone to check over. I have found though that most of the errors are due to it trying to write a user to a group that they have previously been written to. So I need to get the script to check if a user is already in the target group and if so move on to the next. Any an all help is greatly appreciated. 

$ErrorLog = New-Item -Type File -Force "C:\Scripts\CLaireL\ErrorLog.csv"

Import-Csv "C:\scripts\ClaireL\Groups.csv"| ForEach-Object {

#Set Source and Target Groups
$from = $_.SourceColumn
$Too = $_.TargetColumn

#Set Source and Target Group Distinguished Name
$sourceGroup = [ADSI]"LDAP://$From"
$targetGroup = [ADSI]"LDAP://$Too"

"Source Group: $($sourceGroup.samAccountName)"
"Target Group: $($targetGroup.samAccountName)"

"`nCloning Source Group to TargetGroup`n"


 
#get Source members
foreach ($member in $sourceGroup.Member)
{
    Try
    {
        "Adding Member: $member"
        $targetGroup.add("LDAP://$($member)")
         
    }
    Catch
    {
        "Error performing add action Cannot Write, $member, from, $From, to, $Too" | Out-File $ErrorLog -Encoding ASCII -Append
    }

}
""

""
}

February 23rd, 2015 5:12pm

Try it this way:

Import-Csv C:\scripts\ClaireL\Groups.csv |
 ForEach-Object {
    Try {
        
        $sourceGroup = [ADSI]"LDAP://$($_.SourceColumn)"
        $targetGroup = [ADSI]"LDAP://$($_.TargetColumn)"
        
        foreach ($member in $sourceGroup.Member) {
            if ($targetGroup.Member -notcontains $member) {
                $targetGroup.add("LDAP://$($member)")
                Write-Host "Added Member: $member" -ForegroundColor green
            } else {
                Write-host "Group already contains - [$member]" -fore blue -back white
            }
        }
    } Catch {
        Write-Host $_ -ForegroundColor red
    }
}

Try not creating too many variables.  It makes the script harder for you to understand.

Free Windows Admin Tool Kit Click here and download it now
February 23rd, 2015 6:14pm

Thank you Jrv, you are an absolute hero, and thank you for the advice.
February 24th, 2015 1:39pm

Glad is it worked for you.
Free Windows Admin Tool Kit Click here and download it now
February 24th, 2015 1:42pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics