We help IT Professionals succeed at work.

Get AD OU Path

tonelm54
tonelm54 asked
on
Is there a command I can issue on a clients PC which will show where in AD the PC is?

For example, if I ran it on my PC, it should return like:-
dom1\Company1\UK\West Midlands\BU006\Laptops.

Any suggestions?
Comment
Watch Question

Shabarinath RamadasanInfrastructure Architect

Commented:
Get-ADComputer "ComputerName" -Properties * |Select CanonicalName

You need Active Directory module installed .

Refer how to install RSAT for AD Powershell module - https://theitbros.com/install-and-import-powershell-active-directory-module/

Cheers
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
This will return any computer's CanonicalName (and default to the local computer).
Plain ADSI, will run on any Windows machine:
Function Get-AdsiComputerCN([Parameter(ValueFromPipeline=$true)][String]$ComputerName = $env:ComputerName) {
	Process {
		$adsiSearcher = [adsisearcher]"(&(objectCategory=Computer)(name=$($ComputerName)))"
		[void]$adsiSearcher.PropertiesToLoad.Add('canonicalname')
		$adsiSearcher.FindOne().Properties.canonicalname
		$adsiSearcher.Dispose()
	}
}

Open in new window

Author

Commented:
Im liking oBdA solution as dont need to install anything, but how do I call it? In Powershell and just call the function Get-AdsiComputerCN ?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
There are several possibilities, depending mostly in which context you want to run this.
Below is a slightly rearranged version.
If you want to use it in an existing script, just copy it into the script and call it as Get-AdsiComputerCN inside the script.

If you want to use it as a stand-alone script, comment out the first and the last line ("Function ..." and "}", and save it as Get-AdsiComputerCN.ps1 or Whatever.ps1.
Then you can just call it as S:\ome\Path\AdsiComputerCN.ps1

Or you can copy and paste the code as it is into an open PS console, and then use the function while that console is open.

Or you can use the script as module; save it as it is (including the Function ...) as PSTools.ps1 or Whatever.ps1.
To make the function available in PS console, you need to "dot-source" it (note the "<dot><space>" at the beginning):
. "S:\ome\Path\PSTools.ps1"

Open in new window

After that, you have the function(s) defined in PSTools.ps1 available in the PS console.

Function Get-AdsiComputerCN {
Param([Parameter(ValueFromPipeline=$true)][String]$ComputerName = $env:ComputerName)
	Process {
		$adsiSearcher = [adsisearcher]"(&(objectCategory=Computer)(name=$($ComputerName)))"
		[void]$adsiSearcher.PropertiesToLoad.Add('canonicalname')
		$adsiSearcher.FindOne().Properties.canonicalname
		$adsiSearcher.Dispose()
	}
}

Open in new window