Create AD OU and Groups

This topic contains 4 replies, has 3 voices, and was last updated by  Graham Beer 2 years, 5 months ago.

  • Author
  • #34593

    Graham Beer

    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 {
    	Param (
    		[Parameter(HelpMessage = "Set Target OU Path", Position = 0, Mandatory = $true)]
    ##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 = @(
    #Hash Table to use to splat New-ADGroup properties
        $GenricADGroupProperties = @{
            GroupCategory = 'Security'
            GroupScope = 'DomainLocal'
            path = $OUPath 
    #Run ADGroup creation
        foreach ($name in $names) 
                New-ADGroup -Name $name -DisplayName $name @GenricADGroupProperties
                write-host "Created group $name"
                Write-Warning $_.exception.message
    }#End of Function
    Set-SoftwareADGroups -OUPath "OU=Software Groups,OU=Viamonstra,DC=Viamonstra,DC=com"


  • #34606

    Max Kozlov

    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='
  • #34607

    Graham Beer

    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.

  • #34608

    Max Kozlov

    OK, I misunderstood second line, which OU is replaced 🙂
    $OUid, $Path = $oupath -split ',',2 -replace '^OU='
    $Path = 'OU='+$Path
    $OUid, $Path = $oupath -split ',',2
    $OUid = $OUid -replace '^OU='

  • #34611

    Graham Beer

    Your a legend, thanks Max !

You must be logged in to reply to this topic.