Create AD OU and Groups

Hi, I’ve written this script to Create an OU and groups. Tried to make it dynamic and create the OU if it does not exist. It works and i’m fairly happy with it. Just wondering if what I have done is “good PowerShell” or better ways I could achieve what I want.

Function Set-SoftwareADGroups {

	[CmdletBinding()]
	Param (
		[Parameter(HelpMessage = "Set Target OU Path", Position = 0, Mandatory = $true)]
		[ValidateNotNullOrEmpty()]
		[string]$OUPath 
                 )


##Create the Active Directory Groups

#See if Organization Unit exists

Try {
        Get-ADOrganizationalUnit $OUPath -ErrorAction Stop
        $Result = $true
    }
    Catch {
        $Result = $False
    }

if ($Result) {
    Write-host -ForegroundColor Yellow "$OUPath exists"
    }
else {
    $OUid = (($OUPath -split ',')[0] -replace "OU=", " ").Trim()
    $Path = ((($OUPath -replace $OUid, " ").Trim("OU=")).trim()).trim(",")
    
    New-ADOrganizationalUnit -Name $OUid -Path $Path
    Write-Host -ForegroundColor Cyan "Created Directory $_"
    }

#Create new AD groups with use of an array 
    $names = @(
        "SUM_Pilot1",
        "SUM_Pilot2",
        "SUM_Excluded",
        "SUM_MW1",
        "SUM_MW2",
        "SUM_MW3",
        "SUM_SRV_Manual"
    )

#Hash Table to use to splat New-ADGroup properties
    $GenricADGroupProperties = @{
        GroupCategory = 'Security'
        GroupScope = 'DomainLocal'
        path = $OUPath 
    }

#Run ADGroup creation
    foreach ($name in $names) 
        {
         try 
            {
            New-ADGroup -Name $name -DisplayName $name @GenricADGroupProperties
            write-host "Created group $name"
            }
         catch
            {
            Write-Warning $_.exception.message
            }
        }

}#End of Function
Set-SoftwareADGroups -OUPath "OU=Software Groups,OU=Viamonstra,DC=Viamonstra,DC=com"

Thanks!

IMHO, All looks like ok, but too bad with these lines:
$OUid = (($OUPath -split ‘,’)[0] -replace “OU=”, " “).Trim()
$Path = ((($OUPath -replace $OUid, " “).Trim(“OU=”)).trim()).trim(”,”)
Too much trims here…
why you replace “ou=” to " " and Trim() after that instead of just -replace ‘OU=’,‘’ and even -replace ‘ou=’
and there is a great ‘split’ option " (String) -Split (Delimiter)[,(Max-substrings)[,“(Options)”]]
thus You can rewrite you code to elegant

$OUid, $Path = $oupath -split ',',2 -replace '^OU='

Max, thats awesome and looks sooo much better, thanks !

Only small snag is $path is Viamonstra,DC=Viamonstra,DC=com and i need the ‘OU=’ at the start, OU=Viamonstra,DC=Viamonstra,DC=com.

But the OUid is spot on, Software Groups.

OK, I misunderstood second line, which OU is replaced :slight_smile:
then
$OUid, $Path = $oupath -split ‘,’,2 -replace ‘^OU=’
$Path = ‘OU=’+$Path
or
$OUid, $Path = $oupath -split ‘,’,2
$OUid = $OUid -replace ‘^OU=’
:slight_smile:

Your a legend, thanks Max !