Reputation: 921
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
Upvotes: 0
Views: 97
Reputation: 28174
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:
select-object name
in GetCompList
to select-object -expandproperty Name
to get a simple array of namesAdmin_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.
Upvotes: 1