Avatar of Ben Hart
Ben Hart
Flag for United States of America asked on

Powershell script help, get-adcomputer managedby properties

I need to get-content or import-csv a txt list of domain users that I need to match with the managedby atribute for my computer objects then export-csv that list of matching computer hostnames.

So far I have:

import-module activedirectory

get-content "c:\oracle.txt" | foreach $user in $users {get-adcomputer -filter * -properties Managedby -eq $user | export-csv "c:\oraclecomputers.txt"}

Open in new window

PowershellScripting Languages

Avatar of undefined
Last Comment
Ben Hart

8/22/2022 - Mon
Jason Crawford

This should work.  Note you will need to edit to include the actual OU in your environment where computers live:

$results = @()

Get-Content 'c:\oracle.txt' | ForEach-Object {
    $comp = Get-ADComputer -LDAPFilter "(managedby=$_)" -SearchBase 'CN=Computers,DC=domain,DC=local'
    $results += $comp
}

$results | Export-Csv results.csv -NoTypeInformation

Open in new window

Ben Hart

ASKER
Thanks Jason.. I'll try this tomorrow.  I have to ask though, I've been working with powershell for about 3 years now.  What made you format your script like you did?
Ben Hart

ASKER
Hmm errors.  Since we don't use the builtin containers I had to change to OU= but the script runs it just does not populate the csv.  I'm betting its the format of my txt file.

What I was wanting to do was search by common or SAM names, however the ManagedBy field is formatted as such:

Domain.org/People/Employees/IT/IT Staff/Tester, John
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Ben Hart

ASKER
Ok I was right.. the format of our ManagedBy attribute is:

CN=Tester\, John,OU=IT Staff,OU=IT,OU=Employees,OU=People,DC=Domain,DC=org

Which is how I'd have to format my txt/csv file in order to search.  Now I just need to figure out how to take a list of names like Tester, Bob or btester and convert into the format above. Which means I need to convert CN into DistinguishedName.
Jason Crawford

Yes the input values have to match the ManagedBy attribute exactly or it won't work.  A little bleeding might be expected in which case we can trap them in a try catch block.  Feel free to PM me if you want to review the input file together outside the public forum.

I base the format of my scripts off veterans around this site like Qlemo and Will Szymkowski.  I think it makes it more readable and structured.
Ben Hart

ASKER
Thanks Jason.. What do you think of another another get-content piece tying to a dsquery?

Something like:


get-content 'c:\oracle.txt' | foreach-object {
$user = dsquery * domainroot -filter "(&(objectcategory=Person)(objectclass=User) (Samaccountname=$user))"

Open in new window


And then exporting that to a new csv?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ben Hart

ASKER
Ok so full script as it sits right now..

import-module activedirectory

get-content 'c:\oracle.txt' | foreach-object {
$user = dsquery * domainroot -filter "(&(objectcategory=Person)(objectclass=User) (Samaccountname=$user))"
$results += $user
}

$results | export-csv c:\users\bhart.difc\desktop\oracleusers.csv -NoTypeInformation


$results = @()

Get-Content 'c:\users\bhart.difc\desktop\oracleusers.csv' | ForEach-Object {
    $comp = Get-ADComputer -LDAPFilter "(managedby=$_)" -SearchBase 'OU=Workstations,OU=Machines,DC=difc,DC=root01,DC=org'
    $results += $comp
}

$results | Export-Csv c:\users\bhart.difc\Desktop\results.csv -NoTypeInformation

Open in new window


My current issue is that I'm not defining the SamAccountname correctly on line 4.  I'm either having a brain fart or over complicating it..
Jason Crawford

I'm unclear what advantage dsquery has over Get-ADComputer or Get-ADObject.   How are you populating your input .csv file?  I did test this prior to answering, and I populated my input file with actual ManagedBy values
Ben Hart

ASKER
My issue is that I'm on a time crunch.  I'm getting a list of users from the dev group that will likely be in cn or displayname format.  So I will need to convert those to DistinguishedName to correctly match our ManagedBy values.

I'll then use the resulting csv to deploy java security properties to only the computers that need it.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Jason Crawford

The concatenate feature of Excel would work perfectly in that situation.  I've used it many times for lists submitted to IT by HR.
Ben Hart

ASKER
My Excel-Fu is poor, plus I usually prefer to script stuff like this versus messing around in too many spreadsheets but yeah that's def an option too.
Ben Hart

ASKER
But back on point.. what is the correct value for the (SamaccountName=$_____)
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ben Hart

ASKER
Boom got it.

$_

Hmm except the export-csv part.  Output pane shows it correctly getting the DistName values but writes nothing to the CSV. Actually no thats a lie.. one column labeled Length with numerical values in the 6 lines below it.
Ben Hart

ASKER
Ok if I go for a strictly dsquery format then this works:

import-module activedirectory

get-content 'c:\users\bhart.difc\desktop\oracle.txt' | foreach-object {
#$user = 
dsquery * domainroot -filter "(&(objectcategory=Person)(objectclass=User) (Samaccountname=$_))" >>c:\users\bhart\desktop\oracleusers.txt
#$results += $user
}

Open in new window


However the second half is now halting on:

PS C:\Windows\System32\WindowsPowerShell\v1.0> get-adcomputer -ldapfilter
Get-ADComputer : Missing an argument for parameter 'LDAPFilter'. Specify a parameter of type 'System.String' and try again.
At line:1 char:16
+ get-adcomputer -ldapfilter
+                ~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

If I separate out the second half into a new ps1 and run it alone (against the same oracleusers.txt file it completes without error but does not write to the csv.
Ben Hart

ASKER
Entire current script:

import-module activedirectory

get-content 'c:\users\bhart.difc\desktop\oracle.txt' | foreach-object {
 
dsquery * domainroot -filter "(&(objectcategory=Person)(objectclass=User) (Samaccountname=$_))" >>c:\users\bhart.difc\desktop\oracleusers.txt

}

$results = @()

Get-Content 'c:\users\bhart.difc\desktop\oracleusers.txt' | ForEach-Object {
    $comp = Get-ADComputer -LDAPFilter "(managedby=$_)" -SearchBase 'OU=Workstations,OU=Machines,DC=difc,DC=root01,DC=org'
    $results += $comp
}

$results | Export-Csv c:\users\bhart.difc\Desktop\results.csv -NoTypeInformation

Open in new window



It reads the oracle.txt file, runs dsquery and correctly generated oracleusers.txt.  The second half reads the file and runs without error and creates an empty results.csv.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Jason Crawford

Well first the file you generate and subsequently use as the source file for my portion contains the DN surrounded by quotes.  Remove the quotes and it will work.

Second there is a better way to do this than outputting to a file then reading from that file in the same script.  I'm stuck on several calls for the next couple of hours but I'll hop on it as soon as I'm done.
ASKER CERTIFIED SOLUTION
Jason Crawford

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.
Ben Hart

ASKER
Friggin amazing.  Yes precisely what I needed and much cleaner than my rendition.  Thanks Jason.
Jason Crawford

Glad I could help, Ben.  Take care.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Qlemo

No functional change to above, just a simplification:
Import-Module activedirectory

Import-Csv source.csv | Select -Expand SamAccountName | 
  Get-ADUser -Properties distinguishedname |
  % {
    Get-ADComputer -LDAPFilter "(managedby=$_)"
  } |
  Export-Csv results.csv -NoTypeInformation

Open in new window

Jason Crawford

I asked Qlemo to weigh in on simplifying the script I provided, and, as expected, he was able to condense it.  Thanks again, Qlemo.
Ben Hart

ASKER
Very nice!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23