ps/Modules/Alkami.PowerShell.AD/Public/Get-ComputerOU.ps1

35 lines
1.3 KiB
PowerShell
Raw Normal View History

2023-05-30 22:51:22 -07:00
function Get-ComputerOU {
<#
.SYNOPSIS
Retrieves the fully distinguished OU of the current machine
#>
[CmdletBinding()]
Param([string]$machineName)
$logLead = (Get-LogLeadName);
if ([String]::IsNullOrEmpty($machineName)) {
Write-Verbose ("$logLead : `$machineName parameter not specified, using {0}" -f $env:COMPUTERNAME)
$machineName = $env:COMPUTERNAME
}
$ldapString = "LDAP://" + [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().DomainName
$domainRoot = New-Object System.DirectoryServices.DirectoryEntry($ldapString)
$ds = New-Object System.DirectoryServices.DirectorySearcher($domainRoot)
$ds.Filter = "(&(objectClass=computer)(name=$machineName))"
Write-Verbose ("$logLead : Searching domain with filter {0}" -f $ds.Filter)
[System.DirectoryServices.SearchResult]$searchResult = $ds.FindOne()
if ($null -eq $searchResult) {
Write-Output ("$logLead : {0}" -f $errors[0] | Format-List -f)
Write-Warning "$logLead : Unable to find the current computer object"
return $null
}
$distinguishedName = $searchResult.Properties["distinguishedName"]
Write-Verbose ("$logLead : DistinguishedName read as {0}" -f $distinguishedName.Substring($machineName.Length + 4))
return $distinguishedName.Substring($machineName.Length + 4)
}