Skip to content

Instantly share code, notes, and snippets.

@p0w3rsh3ll
Created May 31, 2021 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p0w3rsh3ll/f4aa9bccae864b4249c23b89463d1b6a to your computer and use it in GitHub Desktop.
Save p0w3rsh3ll/f4aa9bccae864b4249c23b89463d1b6a to your computer and use it in GitHub Desktop.
Function Get-ADObjectParentPath {
<#
.SYNOPSIS
Get the parent DN location of an AD object.
.DESCRIPTION
Get the parent DN location of an AD object.
.PARAMETER DistinguishedName
DistinghedNames objects passed as input (from AD cmdlets).
.PARAMETER DN
DistinghedNames strings passed as input
.EXAMPLE
Get-ADUser Skywalker | Get-ADObjectParentPath
.EXAMPLE
'CN=Luc Skywalker,OU=Users,OU=Prod,DC=Star,DC=Wars,DC=com' | Get-ADObjectParentPath
#>
[CmdletBinding(DefaultParameterSetName = 'String')]
Param(
[Parameter(ParameterSetName = 'Obj', Mandatory,ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
$DistinguishedName,
[Parameter(ParameterSetName = 'String', Mandatory,ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[string[]]$DN
)
Begin {
if (-not(Test-Path -Path 'AD:\' -PathType Container)) {
Write-Warning -Message 'Failed to find the AD drive, aborting'
break
}
}
Process {
if ($DistinguishedName) {
$DistinguishedName |
ForEach-Object -Process {
$parent = ((Get-Item "AD:\$($_)" -ErrorAction SilentlyContinue).PSParentPath | Split-Path -NoQualifier ) -replace '//RootDSE/',''
if ($parent) {
$parent
}
}
}
if ($DN ) {
$DN |
ForEach-Object -Process {
if (Test-Path -Path "AD:\$($_)" -ErrorAction SilentlyContinue) {
$parent = ((Get-Item "AD:\$($_)" -ErrorAction SilentlyContinue).PSParentPath | Split-Path -NoQualifier ) -replace '//RootDSE/',''
if ($parent) {
$parent
}
} else {
Write-Warning -Message "Path AD:\$($_) not found"
}
}
}
}
End {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment