We help IT Professionals succeed at work.

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

tbagnation
tbagnation asked
on
600 Views
Last Modified: 2015-09-24
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.
Comment
Watch Question

Will SzymkowskiSenior Solution Architect
CERTIFIED EXPERT
Most Valuable Expert 2015
Top Expert 2015

Commented:
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.
Top Expert 2015

Commented:
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.

Author

Commented:
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.
Top Expert 2015

Commented:
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?

Author

Commented:
To be honest... Both would be great. Thanks Guy!
Top Expert 2015

Commented:
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?
Top Expert 2015

Commented:
By the way... this is turning into a beast of a script... so much for scratching something up... almost done though.
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks guy! Is this complete? I appreciate your effort here.

Author

Commented:
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!
Top Expert 2015

Commented:
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).

Author

Commented:
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
Top Expert 2015

Commented:
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

Author

Commented:
Hey Guy - is it possible to make it so that any property can be selected and exported to a CSV?
Top Expert 2015

Commented:
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.

Author

Commented:
Guy - You are a rock star! thanks!

Author

Commented:
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.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.