0

I'm writing a script to find local admins on machines in a specific OU. I've created two functions to preform this task, each function by itself is working fine, but when I combine the two I am not getting any result. Anyone know what I'm doing wrong here?

    Function GetCompList{
Get-ADObject -Filter { ObjectClass -eq "computer" } -SearchBase "OU=Resources,DC=Contoso,DC=LOCAL" `
| Select-Object Name
}

Function Admin_Groups{
foreach($i in GetCompList){
$adsi = [ADSI]"WinNT://$i"
$Object = $adsi.Children | ? {$_.SchemaClassName -eq 'user'} | % {
    New-Object -TypeName PSCustomObject -Property @{
        UserName = $_.Name -join ''
        Groups = ($_.Groups()  |Foreach-Object {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}) -join ',' 
    }    
} 
$Object |? {$_.Groups -match "Administrators*"}

}
}

Admin_Groups

1 Answer 1

1

Your GetCompList function is returning a collection of objects. You're probably getting this when you run the one function:

Name
------
Comp1
Comp2
Comp3

In the foreach loop of Admin_Groups, you're using the output of GetCompList as an array of primitives - just a list of names, not a bunch of objects. So, you have two options:

  1. Change the select-object name in GetCompList to select-object -expandproperty Name to get a simple array of names
  2. In Admin_Groups, change each reference to $i in the body of the foreach loop to $i.Name. Since you're using it within a string, it's a little ugly to do that.

In this particular example, my preference would be option #1, making that function:

Function GetCompList{
    Get-ADObject -Filter { ObjectClass -eq "computer" } -SearchBase "OU=Resources,DC=Contoso,DC=LOCAL" | Select-Object -expandproperty Name
}

I would also suggest that you rename your functions to match the Verb-Noun convention of PowerShell, and use one of the approved verbs from get-verb.

Get-CompList
Get-AdminGroups

Failing that, at least make your function names consistent - either use the _ to separate the words in the names, or don't. Don't mix & match.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.