Search code examples
powershellpowershell-5.0

How to simplify if/else code if I have a common pattern


From how I understand it, I am not looking for an if statement, or an elseif statement. In a foreach statement, I am trying to check X, and do one thing, check Y, and do that too, check Z, and do something different for that too.

Here is my current code:

    #5 | Add-UserToGrp and adding each user in their OUs to their respective Groups
Function Add-UserToGrp
{
    $OUusers = Import-Csv -Path "C:\MyScripts\FinalProject\csv\createUsers.csv"

    foreach($OU in $OUusers)
    {
        $user   = $OU.OUName
        $oupath = $OU.OUPath

        if($oupath -eq "Sales_OU")
        {
            Add-ADGroupMember -Identity "CN=SalesGrp,CN=Users,DC=PT,DC=LOCAL" -Members "CN=$user,OU=SalesOU,DC=PT,DC=LOCAL"
        }
        if($oupath -eq "HR_OU")
        {
            Add-ADGroupMember -Identity "CN=HRGrp,CN=Users,DC=PT,DC=LOCAL" -Members "CN=$user,OU=HR_OU,DC=PT,DC=LOCAL"
        }
    }

Is there some magical statement that will do what I want? I saw something about foreach -parallel that maybe was what I wanted, but it has to be in a workflow and I don't think that's the right direction to go. I need to run like 10 of these if statements and execute code after all of them, within a foreach statement.

Please tell me if I did a poor job explaining or you need me to clarify anything. Thanks in advance for your assistance.


Solution

  • Assuming all possible values of your OUPath are in the same format, this will simplify your logic without the if/else structure. You had the basics right before, aside from the typo.

    Function Add-UserToGrp
    {
        $OUusers = Import-Csv -Path "C:\MyScripts\FinalProject\csv\createUsers.csv"
    
        foreach($OU in $OUusers)
        {
            $user   = $OU.OUName
            $oupath = $OU.OUPath
    
            # Get everything before OU in $path, with an optional _ between the first part and the OU.  HR_OU becomes HR.  SomethingElseOU becomes SomethingElse.
            $null = ($oupath -imatch "([^_]+)_?OU")
            $path = $matches[1]
    
            # this combines the $path part into a combined string with the Grp. HR becomes HRGrp.  Sales becomes SalesGrp.
            Add-ADGroupMember -Identity "CN=$($path)Grp,CN=Users,DC=PT,DC=LOCAL" -Members "CN=$user,OU=$oupath,DC=PT,DC=LOCAL"
        }