Private/Initialize-LinuxOU.ps1
|
function Initialize-LinuxOU { <# .SYNOPSIS Creates the target OU for Linux servers if it does not already exist. #> [CmdletBinding()] param( [Parameter(Mandatory)] [string]$OrganizationalUnit ) try { $null = Get-ADOrganizationalUnit -Identity $OrganizationalUnit -ErrorAction Stop Write-Verbose "OU already exists: $OrganizationalUnit" } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { Write-Verbose "OU not found. Creating: $OrganizationalUnit" # Parse the OU name and parent path from the distinguished name # Example: "OU=Linux Servers,DC=contoso,DC=com" -> Name="Linux Servers", Path="DC=contoso,DC=com" $parts = $OrganizationalUnit -split ',', 2 $ouName = ($parts[0] -replace '^OU=', '') $parentPath = $parts[1] try { New-ADOrganizationalUnit -Name $ouName -Path $parentPath ` -Description 'Linux and non-Windows server inventory - managed by AD-LinuxInventory module' ` -ProtectedFromAccidentalDeletion $true ` -ErrorAction Stop Write-Verbose "Created OU: $OrganizationalUnit" } catch { throw "Failed to create OU '$OrganizationalUnit': $_" } } catch { throw "Failed to verify OU '$OrganizationalUnit': $_" } } |