powershellvariablesps1

Powershell variable issue Get-Content and Get-ADGroup


I'm trying to figure out the reason why I can run the script using variable $groups with Get-Content but it wont work if variable $groups goes with Get-ADGroup list I did below...

Block that works:

$groups = Get-Content C:\groups.csv 

$results = @()

$file = "C:\Usuarios_Grupos_Darwin_AD.csv"  

foreach($Group in $Groups) { 

$results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Identity $_.SamAccountName -Properties Enabled,Name} | Select @{Expression={$Group};Label=”Group Name”},SamAccountName,Name,Enabled

}

$results | export-csv -notypeinformation -Delimiter ";" -path $file 

Block that's not working: (only the first line has been changed)

$groups = Get-ADGroup -Filter {Name -like '*Darwin*'}  -Properties * | select -property Name

$results = @()

$file = "C:\Usuarios_Grupos_Darwin_AD.csv"  

foreach($Group in $Groups) { 

$results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Identity $_.SamAccountName -Properties Enabled,Name} | Select @{Expression={$Group};Label=”Group Name”},SamAccountName,Name,Enabled

}

$results | export-csv -notypeinformation -Delimiter ";" -path $file

Here is the error:

Get-ADGroupMember : Cannot bind parameter 'Identity'. Cannot create object of type "Microsoft.ActiveDirectory.Management.ADGroup". The adapter cannot set the value of property 
"Name".
At line:11 char:34
+ $results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Id ...
+                                  ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember

I'm trying to embed the output list all in one script without having to generate csv with another script.

Thanks in advance !!


Solution

  • A few notes about your code:

    Try this:

    # Get-ADGroup already returns objects with these properties:
    # DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
    $groups = Get-ADGroup -Filter "Name -like '*Darwin*'"
    $file = "C:\Usuarios_Grupos_Darwin_AD.csv"  
    # let PowerShell collect the objects for you instead of using +=
    $results = foreach($Group in $Groups) { 
        # Get-ADGroupMember can return objects of type users and computers (also groups when used without -Recursive)
        # so filter the result to get only user objects
        $Group | Get-ADGroupMember -Recursive | Where-Object { $_.objectClass -eq 'user' } | ForEach-Object {
            $_ | Get-ADUser | Select @{Name = 'Group Name'; Expression={$Group.Name}}, SamAccountName, Name, Enabled
        }
    }
    
    $results | Export-Csv -Path $file -NoTypeInformation -Delimiter ";"