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!