Help creating a powerShell script that will pull all users from an OU and display the properties desired  (also if possible exclude disabled account)

Hi,

I am trying to create a script for our HR Dept that will pull up a list of -properties and display them them for all users in a OU minus disabled accounts.  (the disabled accounts is not required as we usually move disabled users to another OU but would be nice to add if its simple and does not cause issues with the script).

So far I have the following:

-------------------------------------------


Get-ADUser -Properties DisplayName,EmailAddress,department,manager -Filter 'name -like "*"' -searchbase "ou=canada,ou=americas,OU=main,dc=test,dc=net,dc=int"


Department        : Sales
DisplayName       : john doe
DistinguishedName : CN=john.doe,OU=Users,OU=woodsville,OU=Canada,OU=AMERICAS,OU=MAIN,DC=test,DC=NET,DC=INT
EmailAddress      : john.doe@test.com
Enabled           : True
GivenName         : john
Manager           : CN=jane doe,OU=Users,OU=smallville,OU=USA,OU=AMERICAS,OU=MAIN,DC=test,DC=NET,DC=INT
Name              : john.doe
ObjectClass       : user
ObjectGUID        : xxxxxxxxxxxxxxxxxxxxxxx
SamAccountName    : john.doe
SID               : xxxxxxxxxxxxxxxx
Surname           : doe
UserPrincipalName : john.doe@test.com


-------------------------------------------

Issues I am having:

1. I cannot get job title, country/region to work and I get error when I add those.  I tried qoutes but maybe in the wrong place? I need those    added to the script.

2. is there a way to get rid of the other fields so it only shows the fields I am asking for?


3. can I add a line that will exclude disabled users should any accidentally be in the OU I am running this against?


4. right now I am writing this to run on one OU, then I would change the OU to the next OU and run it.    Is there a way I can put all the OU in the same script so that I run this script once and it will pull the users from say 10 different OU and output that info?

any help would be appreciated as I am still learning PS and a babe in this field compared to many.

Thanks,

April 30th, 2015 12:26pm

Start off simple first. -Filter 'Name -eq "*"' is not needed, Get-ADUser -Filter * will return all users. The issue with the properties you want may be the name you are supplying. The easiest way to see the properties is grab one user

Get-ADUser myUserNmae -Prop *

This will list every property available, once you have that, you can add each on to the property list. To only select a subset of properties, you pipe over to the Select-Object cmdlet and select what properties you want to see.
Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 12:30pm

A finalized version would be something like so

$props = @('EmailAddress',
           'Department',
		   'Manager',
		   'Title',
		   'Country')
				
$ous = @("ou=canada,ou=americas,OU=main,dc=test,dc=net,dc=int")

$ous | ForEach {
  Write-Output "Accessing OU $_"
  Get-ADUser -Properties $props -Filter 'Enabled -eq $true' -SearchBase $_ | Select Name, EmailAddress, Department, Title, Country
 }

This will return only enabled users with the properties that you are requesting. For more OU's, just add to the array, making sure each entry is followed by a comma, just like the $props array.

April 30th, 2015 12:51pm

ok that did allow me to figure out the properites and the question listed in   "1"

co                                   : United States

Country                              : US

EmployeeID                           :
EmployeeNumber                       :

Title                                : Client & Server Support Engineer

=====================

that was very helpful.

Is there anyway to do the other three?

2. is there a way to get rid of the other fields so it only shows the fields I am asking for?


3. can I add a line that will exclude disabled users should any accidentally be in the OU I am running this against?


4. right now I am writing this to run on one OU, then I would change the OU to the next OU and run it.    Is there a way I can put all the OU in the same script so that I run this script once and it will pull the users from say 10 different OU and output that info?

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 12:59pm

ok I just saw this missed it earlier let me look this over!
April 30th, 2015 1:12pm

Ok let me ask questions on this one.  I have never been very good with that " '  "  sign to make a line end but I will test it out.

So  your creating the variable #props and storing all the property information into it

then you create the variable  $ous and store the UO into that

I am having trouble understanding what you do here fully

$ous | ForEach {
  Write-Output "Accessing OU $_"

also there part below I see the searchbase which I understand, is the pipe and select command telling it what you want to output?

-SearchBase $_ | Select Name, EmailAddress, Department, Title, Country
 }

Sorry for not fully understanding all the parts it just helps me to be able to recreate if I fully understand what I am using.  I understand most everything just need it pulled together.  If I was not clear in what I was not understanding please let me know and I will try to state it better.

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 1:23pm

Since $ous is an array, I am just piping it over to the Foreach-Object (ForEach just to shorten it) to loop through each entry.

So -SearchBase will be $_ which is the current pipeline object, grab all of the users and then pipe over to the Select-Object cmdlet. This cmdlet allows you to select the properties of an object you want to display, and there is other advanced stuff you can do with Select-Object, but in your case it is not n

April 30th, 2015 1:33pm

I did try the script but getting errors:

-----------------------------------

PS C:\Windows\system32> $props = @(DisplayName,EmailAddress,Department,Manager,Title,Country) $ous =("ou=canda,ou=americ
as,ou=main,dc=test,dc=net,dc=int") $ous | ForEach { Write-output "Accessing ou $_"Get-ADUser -Properties $props -Filter 'Enabled -eq $true' -searchbase $_ | Select Name, EmailAddress,Department,Title,country,DisplayName}



At line:1 char:23
+ $props = @(DisplayName,EmailAddress,Department,Manager,Title,Country) $ous =("ou ...
+                       ~
Missing argument in parameter list.
At line:1 char:71
+ $props = @(DisplayName,EmailAddress,Department,Manager,Title,Country) $ous =("ou ...
+                                                                       ~~~~
Unexpected token '$ous' in expression or statement.
At line:1 char:134
+ ... c=net,dc=int") $ous | ForEach { Write-output "Accessing ou $_"Get-ADUser -Proper ...
+                    ~~~~
Unexpected token '$ous' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument

PS C:\Windows\system32>

-------------------------------------------------------

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 1:38pm

Sounds to me like you have white space or a formatting issue. Are you copying and pasting directly into Powershell console, or an ISE?
April 30th, 2015 1:47pm

ok I put it in like you did with the lilt "  '   "  and it seemed to work I changed some of the info ofcourse becaues this is public forums

PS C:\Windows\system32> $props = @('EmailAddress',
>> 'Department',
>> 'Title',
>> 'Country')
>> $ous = @("ou=canada,ou=americas,ou=main,dc=marine,dc=net,dc=int")
>> $ous | foreach {
>> Write-output "Accessing OU $_"
>> Get-ADUser -Properties $props -Filter 'Enabled -eq $true' -SearchBase $_ | select Name,EmailAddress,Department,title,
Country}
>>
Accessing OU ou=canada,ou=americas,ou=main,dc=test,dc=net,dc=int


Name         : john.doe
EmailAddress : john.doer@test.com
Department   : Sales
title        : Territory Manager
Country      : CA

Name         : john.doe
EmailAddress : john.doer@test.com
Department   : Sales
title        : Territory Manager
Country      : CA

Name         : john.doe
EmailAddress : john.doer@test.com
Department   : Sales
title        : Territory Manager
Country      : CA

Name         : john.doe
EmailAddress : john.doer@test.com
Department   : Sales
title        : Territory Manager
Country      : CA



PS C:\Windows\system32>

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 1:47pm

Yes the elements in the arrays need to be in cased in either single quotes '' or double quotes "" to denote they are strings.
April 30th, 2015 1:48pm

does it allow you to add different OU? so it will search multiple ou

I dont fully understand the entire script so I could not manipulate this.  Its just a little bit from my really simple powershell command to this.

so I am struggling a bit to make sense of everything down to the detail.

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 2:07pm

Yes it can process more OU's, you just need to update the $ous array with the others you would like

$ous = @("ou=myou,dc=mydomain,dc=com",
         "ou=anotherOU,ou=myou,dc=mydomain,dc=com")

Just make sure each string is enclosed in either single or double quotes, and each entry is separated by a comma, except for the last one.

I would start reading some material on Powershell to get a better understanding on what is going on.

PowerShell Tutorial

You can also search google, there is a ton of information out there.

April 30th, 2015 2:15pm

Ok that makes a bit more sense to me

So the @ sign is saying to use array and we are putting these arrays into that variable $ous

which is why we have the For Each?

---------------------------------------------

ok and I can now get it to pipe by adding that in.   

-----------

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 2:28pm

No the @() indicates an array, as a hashtable would be @{}. Yes we are using the Foreach loop to iterate through each element of the array. Some cmdlets will take in arrays as a parameter, like the -Properties param of Get-ADUser.

You can get detailed information about cmdlets by doing

Get-Help <cmdletName> -Detailed

Get-Help Get-ADUser -Detailed

April 30th, 2015 2:31pm

ok this power shell script did everything I needed and rocked.  After making some minor modifications with our data my boss was very happy.  Thanks!
Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 5:05pm

Hey Clayman,

I had a question when I run my script it will output no problem to txt file.    However, I wanted to get it in CSV file and I am getting an empty CSV file except for the following information:

------------------------------

#TYPE System.String
"Length"
"66"

 

"66"

----------------------------------

at first I thought this was because I had a syntax but on closer look and after I put in the correct syntax i am still getting it.   any ideas?

I am just running the code here:

------------------------------------

$ous | ForEach {
  Write-Output "Accessing OU $_"
  Get-ADUser -Properties $props -Filter 'Enabled -eq $true' -SearchBase $_ | Select Name, EmailAddress, Department, Manager, Title, Country
} | export-csv -path c:\scripts\data.csv

------------------------------------------

if I run the same code to a text file it works, but I am needing this in CSV form and not sure what the deal is.

May 1st, 2015 10:45am

Hi,

Remove the Write-Output line and try again.

I'd also suggest adding -NoTypeInformation to your Export-Csv command.

Free Windows Admin Tool Kit Click here and download it now
May 1st, 2015 10:47am

Hi

Thanks I will try that.  I also found this link which may explain it as well I was reading it when I heard my email go off frtom the forums.

http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/23/use-powershell-to-work-with-csv-formatted-text.aspx

May 1st, 2015 10:49am

Ok I took out the  Write-Output line

--------------------------------

$ous | ForEach {
      Get-ADUser -Properties $props -Filter 'Enabled -eq $true' -SearchBase $_ | Select Name, EmailAddress, Department, Manager, Title, Country
 } | export-csv -path c:\scripts\data.csv

---------------------------------

Mike can you explain specifically whaqt the write-0utput line does is that just saying output to the screen what does that mean?

Free Windows Admin Tool Kit Click here and download it now
May 1st, 2015 10:55am

Yes Write-Output was put there to print out to the console, so you can see what OU you are processing at the time.
May 1st, 2015 11:00am

Thanks!

I love you guys lol... if your ever in Tulsa oklahoma look holler at me I will buy you lunch!

Free Windows Admin Tool Kit Click here and download it now
May 1st, 2015 11:05am

Cheers, glad we could help out and thanks for the offer. =]
May 1st, 2015 12:13pm

Thanks found very usefull.

Regards

Raj

Free Windows Admin Tool Kit Click here and download it now
May 1st, 2015 1:04pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics