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.
tbagnationAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Will SzymkowskiSenior Solution ArchitectCommented:
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.
0
Guy LidbetterCommented:
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.
1
tbagnationAuthor 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.
0
How do you know if your security is working?

Protecting your business doesn’t have to mean sifting through endless alerts and notifications. With WatchGuard Total Security Suite, you can feel confident that your business is secure, meaning you can get back to the things that have been sitting on your to-do list.

Guy LidbetterCommented:
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?
0
tbagnationAuthor Commented:
To be honest... Both would be great. Thanks Guy!
0
Guy LidbetterCommented:
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?
0
Guy LidbetterCommented:
By the way... this is turning into a beast of a script... so much for scratching something up... almost done though.
0
Guy LidbetterCommented:
Here's the script so far.

Save it as "Get-CNUser.ps1".

Run the below command to get help on using it
Help .\Get-CNUser -full

Open in new window


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.
	    
	.EXAMPLE
    Get an individual user by CNAME 
    .\Get-CNUser.ps1 -CNAME "test.com/users/ou/Username"
	
	Get all users in Sales Department OU and subfolders by CNAME
	.\Get-CNUser.ps1 -CNAME "test.com/OU/Users/Sales Department" -isOU $True -SearchSubs $True
	
    #>

# Define Parameters

param(
    [parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false,HelpMessage='Canonical Name')][string]$CNAME,
	[parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Is this an OU ($True/$False)')][bool]$isOU=$False,
	[parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Search Subfolders of OU ($True/$False)')][bool]$SearchSubs=$True
)

# 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(",")
	GetADUser
}

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(",")
	GetADUser
}

Function getADUser {
	IF ($isOU) {
		IF ($SearchSubs) {
			Get-ADUser -Filter * -SearchBase $DName -SearchScope 2 | FL *
		}
		ELSE {
			Get-ADUser -Filter * -SearchBase $DName -SearchScope 1 | FL *
		}
	}
	Else {
		Get-ADUser $Dname | FL *
	}

}

readParams

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tbagnationAuthor Commented:
Thanks guy! Is this complete? I appreciate your effort here.
0
tbagnationAuthor 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!
0
Guy LidbetterCommented:
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).
0
tbagnationAuthor 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
0
Guy LidbetterCommented:
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

0
tbagnationAuthor Commented:
Hey Guy - is it possible to make it so that any property can be selected and exported to a CSV?
0
Guy LidbetterCommented:
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.
0
tbagnationAuthor Commented:
Guy - You are a rock star! thanks!
0
tbagnationAuthor 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.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.