Avatar of tbagnation
tbagnation
 asked on

How to query Active Directory objects via an organizational unit easiest in Powershell by Canonical naming format

I would like to locate AD objects with the AD Powershell Module, but use Canonical naming format instead of Distinguished Name.

Get-aduser test.com/users/ou as an example but don't know the best method to to do so.
PowershellActive Directory

Avatar of undefined
Last Comment
tbagnation

8/22/2022 - Mon
Will Szymkowski

Unfortuneately you only have four options when it comes to querying by the Identity Parameter. These values are sAMAccountName, DistinguishedName, SID and GUID.

You also will not be able filter on CanonicalName either because it is a Constructed Attribue and it is not part of the default properties. So i am not exactly sure whatyou want to do with the CanonicalName.

I have also checked Get-adobject and it also does not accept CanonicalName and a searchable attribute.

Will.
Guy Lidbetter

Hi TBag

Your only option to use a CN would be to create your own script with a function which breaks down the CN which is entered as a parameter, constructs a DistinguishedName, and then queries based on that.

If you have an absolute requirement for that, i.e. you only have CN's and absolutely have to use them, then I could see if I could script it up for you.
tbagnation

ASKER
That would be great. If you could supply a scripted option in Powershell that would be great. I just want to be able to search/view/query objects in Powershell basically by using the Canonical Path instead of DN, etc. So, maybe I wasn't clear enough.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Guy Lidbetter

No, You were perfectly clear... I'll scratch something up for you today...

Are you looking to get-aduser on individual users or entire OU's as well?
tbagnation

ASKER
To be honest... Both would be great. Thanks Guy!
Guy Lidbetter

Hi TBag,

Quick question... What user properties are you looking for?
Properties you are able to extract from Powershell are listed here: http://social.technet.microsoft.com/wiki/contents/articles/12037.active-directory-get-aduser-default-and-extended-properties.aspx

Also, are you looking to export the values or will just screen output be sufficient?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Guy Lidbetter

By the way... this is turning into a beast of a script... so much for scratching something up... almost done though.
ASKER CERTIFIED SOLUTION
Guy Lidbetter

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
tbagnation

ASKER
Thanks guy! Is this complete? I appreciate your effort here.
tbagnation

ASKER
Guy -

My apologies... I didn't answer your first question, but I am really just looking for screen output, but exporting the data would be a plus too.

Thanks!
Your help has saved me hundreds of hours of internet surfing.
fblack61
Guy Lidbetter

For just screen output, yes that's all done.

I'll add an additional parameter to export the results. Can you confirm the properties you are looking to get out of this?

What I could do is if you want to output to screen, just the canned properties will be displayed, but if you want an export - everything including the kitchen sink (See above posted URL) will be output (Unless you want to specify the exact properties you are looking for).
tbagnation

ASKER
Thanks for this guy!

OK. So, I would like to get Name, Displayname, employeeID, Samaccountname, Emailaddress.

One question... Can I use this with this parameter below? Using the | select name

.\Get-CNUser.ps1 -CNAME "Tribunemedia.com/TMUsers/Test Accounts" -isOU $true | select name
Guy Lidbetter

OK, so I've updated the script to include an export function and the ability to select specific properties.

You would not use the select command for this, instead use the -Props parameter as explained in the examples.

Run this for Usage Examples:
help .\Get-CNUser -Examples

Open in new window


And here is the script
<#
    .SYNOPSIS
    Search for Users using privided Canonical Names (CNAME) of User or OU.
   
   	Guy Lidbetter
	
	THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE 
	RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
	
	Version 1.0 21st September 2015
	
    .DESCRIPTION
	
    This script uses a provided Canonical Name (CNAME) to locate accounts using the ActiveDirectory
	module cmndlet Get-ADUser.
		
	IMPORTANT NOTE: This script requires the ActiveDirectory Module as installed with RSAT tools if not run on a domain controller.
	
	.PARAMETER CNAME
    The CNAME to be searched with Get-ADUser
	
	.PARAMETER isOU
	CName is for an OU. Set to $True to enable. If enabled script will call all users in the OU and subfolders.
	
	.PARAMETER SearchSubs
	Search Subfolders of OU as well. Set to $False to disable. Enabled by default. If disabled, search will return only users in selected OU.
	
	.PARAMETER Props
	Specify the properties to query from AD. Default is all available. Specific properties can be requested through comma seperated list. See Example 3.
	
	.PARAMETER Export
	Export the results to a CSV File. Set to $True to enable. If enabled script will export only to CSV with no screen output. This is better for querying a lot of properties.
	
	.PARAMETER Filepath
	Filepath to Export CSV to. Default is "C:\Temp\User Export.csv"
	    
	.EXAMPLE
    Get an individual user.
	.\Get-CNUser.ps1 -CNAME "Domain.com/Headoffice/Users/User name"
	
	.EXAMPLE
	Get all users in Sales Department OU and subfolders.
	.\Get-CNUser.ps1 -CNAME "Domain.com/Offices/Sales Department/Users" -isOU $True -SearchSubs $True
	
	.EXAMPLE
	Get an individual with specific properties.
	.\Get-CNUser.ps1 -CNAME "Domain.com/Users/User name" -Props Name, Displayname, employeeID, Samaccountname, Mail
	
	.EXAMPLE
	Get all users in root Finance Department OU only and Export Results to CSV.
	.\Get-CNUser.ps1 -CNAME "Domain.com/Headoffice/Departments/Finance/Users" -isOU $True -SearchSubs $False -Export $True -Filepath "C:\Rootfolder\Subfolder\results.csv"
	
    #>

# Define Parameters

param(
    [parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false,HelpMessage='Canonical Name')][string]$CNAME,
	[parameter(Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Is this an OU ($True/$False)')][bool]$isOU=$False,
	[parameter(Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Search Subfolders of OU ($True/$False)')][bool]$SearchSubs=$True,
	[parameter(Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Export Report to CSV')][bool]$Export=$False,
	[parameter(Mandatory=$false,ValueFromPipeline=$false,HelpMessage='FilePath to Exported Report')][String]$Filepath="C:\Temp\User Export.csv",
	[parameter(Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Required Properties (Comma Seperated)')][string[]]$Props="*"
	
)

# Import Modules
Import-Module ActiveDirectory

# Define Functions

Function readParams {
	IF ($isOU) {
		getOU
	}
	ELSE {
		getUser
	}
}
	
	
Function getOU {	
	$Working = $CNAME.split('/')
	$DNWorking = $Working[0]
	$DNWorking = $DNWorking.split('.')
	$OUWorking = $Working[1..500]
	[array]::Reverse($OUWorking)
	$OUWorking = $OUWorking | foreach {"OU=$_"}
	$DNWorking = $DNWorking | foreach {"DC=$_"}
	[String]$DName = ""
	$OUWorking | foreach {$DName = $DName + $_ + ","} 
	$DNWorking | foreach {$DName = $DName + $_ + ","} 
	$DName = $DName.Trim(",")
	IF ($Export) {
		GetADUserExport
	}
	ELSE {
		GetADUserDisp
	}
}

Function getUser {	
	$Working = $CNAME.split('/')
	$DNWorking = $Working[0]
	$DNWorking = $DNWorking.split('.')
	$OUWorking = $Working[1..500]
	[array]::Reverse($OUWorking)
	$CNWorking = $OUWorking[0]
	$OUWorking = $OUWorking[1..500]
	$CNWorking = $CnWorking | foreach {"CN=$_"}
	$OUWorking = $OUWorking | foreach {"OU=$_"}
	$DNWorking = $DNWorking | foreach {"DC=$_"}
	[String]$DName = ""
	$CNWorking | foreach {$DName = $DName + $_ + ","} 
	$OUWorking | foreach {$DName = $DName + $_ + ","} 
	$DNWorking | foreach {$DName = $DName + $_ + ","} 
	$DName = $DName.Trim(",")
	IF ($Export) {
		GetADUserExport
	}
	ELSE {
		GetADUserDisp
	}
}

Function getADUserDisp {
	IF ($isOU) {
		IF ($SearchSubs) {
			Get-ADUser -Filter * -SearchBase $DName -SearchScope 2 -Properties $Props | Select $Props
		}
		ELSE {
			Get-ADUser -Filter * -SearchBase $DName -SearchScope 1 -Properties $Props | Select $Props
		}
	}
	Else {
		Get-ADUser $Dname -Properties $Props | Select  $Props
	}

}

Function getADUserExport {
	IF ($isOU) {
		IF ($SearchSubs) {
			Get-ADUser -Filter * -SearchBase $DName -SearchScope 2 -Properties $Props | Select $Props | Export-CSV $FilePath -NoTypeInformation
		}
		ELSE {
			Get-ADUser -Filter * -SearchBase $DName -SearchScope 1 -Properties $Props | Select $Props | Export-CSV $FilePath -NoTypeInformation
		}
	}
	Else {
		Get-ADUser $Dname -Properties $Props | Select $Props | Export-CSV $FilePath -NoTypeInformation
	}

}

readParams

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
tbagnation

ASKER
Hey Guy - is it possible to make it so that any property can be selected and exported to a CSV?
Guy Lidbetter

It already does that .. eg.

.\Get-CNUser.ps1 -CNAME "Domain.com/Headoffice/Departments/Finance/Users" -isOU $True -SearchSubs $True -Export $True -Filepath "C:\Rootfolder\Subfolder\results.csv" -Props Name, Displayname, employeeID, Samaccountname, Mail

Open in new window


I would you suggest you read the help file I included.
tbagnation

ASKER
Guy - You are a rock star! thanks!
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
tbagnation

ASKER
I've requested that this question be closed as follows:

Accepted answer: 0 points for tbagnation's comment #a40996084

for the following reason:

Not sure I understand.