Looking to extract information using powershell

278 views Asked by At

I need to extract information using a powershell cmdlet and a txt file.

The TXT file contains a list of groups

I want to first feed powershell the script... pretty simple:

get-content c:\scripts\mygroups.txt

I then want to run a Foreach-object cmdlet against it and pull only the distinguished name

The problem is that I keep running into the -Filter command and I shouldn't need the filter command because the names are exactly pulled from AD.

Foreach-Object {Get-ADGroup -Filter "*" | select DistinguishedName} works but I dont want all the groups I want the variable that I used for the get-content command. I feel I am missing some type of link between the -Filter and selecting the field I want to display. Please help me link the two together. Thanks!

Here is the error I am getting... Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup

3

There are 3 answers

0
Keith Hill On

Assuming that each group name is on a line in the file and there are no blank lines, try this:

Get-Content c:\scripts\mygroups.txt | Foreach {Get-ADGroup $_} | 
    Select DistinguishedName
0
MasterOfTheHat On

You could actually take out the "Foreach" part of Keith's code and just let the pipeline do the loop for you:

Get-Content c:\scripts\mygroups.txt | Get-ADGroup | Select DistinguishedName

This is still assuming that the text file contains the group names, ("Name" attribute), with only one group name per line.

0
Shay Levy On

Pipe the content of the file to the Get-ADGroup cmdlet and expand the DistinguishedName of each output object:

Get-Content c:\scripts\mygroups.txt | 
Get-ADGroup | 
Select-Object -ExpandProperty DistinguishedName