Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Feeding a Foreach Loop Into A Function

Status
Not open for further replies.

Brycspain

IS-IT--Management
Mar 9, 2006
150
US
Markdmac sent me this really nice function that converts the sAMAccountName into a Distinguished name. I have a text file with 600 or so usernames that I would like to feed into this function using a foreach loop and send the output to the screen. I am having no luck finding examples on the net on how to do this. I've tried everything I can think of to get this script to work. Any help would be appreciated.

Here is the code:

Code:
$a = (get-content usernames.txt)
foreach ($name in $a)
[b]{Write-Ouput | Get-DistinguishedName([string]$name)}[/b]


#
function Get-DistinguishedName {
#
Param($username)
#
    $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
#
    $ads.filter = "(&(objectClass=Person)(samAccountName=$username))"
#
    $s = $ads.FindOne()
#
    return $s.GetDirectoryEntry().DistinguishedName
#
}
 
I see the first problem already, the function has to be defined first before you can call on it. I did try to reverse the code but had no luck with that too.
 
I worked on this all day but only after I posted asking for help did I realize one more thing and I figured it out. Just being around you guys makes me smarter =)

Code:
#
function Get-DistinguishedName {
#
Param($username)
#
    $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
#
    $ads.filter = "(&(objectClass=Person)(samAccountName=$username))"
#
    $s = $ads.FindOne()
#
    return $s.GetDirectoryEntry().DistinguishedName
#
}


$a = (get-content usernames.txt)
foreach ($username in $a)
{Get-DistinguishedName($username) | write-output}
 
is the bit about the function not being declared first really true? does it really matter 'where' it comes in the script?
 
Yep...function needs to be declared first.

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
thanks dm4ever, i need to start learning Powershell but after yawning my way though O'Reilly;s book i am a little reluctant
 
I know how you feel Mr, I'm basically forcing myself to learn Powershell. Don Jones is coming out with a new book pretty soon that should make it easier.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top