tsla3
tsla3

Reputation: 13

Am I doing something wrong with my PowerShell array?

I'm trying to prepend any groups the user is a member of with "MW-" (that is working). But when I try to do a loop to add another user to those group names with the "MW-" that I stored in $var I get an error

Cannot bind parameter 'Identity'. Cannot convert value "@{MW-" + $_.name=MW-DFS-share1}" to value of type "Selected.Microsoft.ActiveDirectory.Management.ADGroup"

$var = Get-ADUser -Identity TestUser -Properties memberof |
       Select-Object -ExpandProperty memberof |
       Where {$_ -match "CN=DFS*"} |
       Get-ADGroup -Properties name |
       Select-Object {"MW-"+ $_.name}

foreach ($group in $var) {
    Add-ADGroupMember -Identity $group -Member TestUser
}

Note; When I run the Get-ADUser command it produces the output below:

"MW-"+ $_.name
--------------
MW-DFS-share1
MW-DFS-files
MW-DFS-archive

Upvotes: 1

Views: 176

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25031

A calculated property is the easiest way to fix your issue. Then you need to either expand that property or access the property directly in your loop.

$var = Get-ADUser -Identity TestUser -Properties memberof |
           Select-Object -ExpandProperty memberof |
               Where {$_ -match "CN=DFS*"} |
                   Get-ADGroup -Properties name |
                       Select-Object @{Label='Name';Expression={"MW-"+ $_.name}}

foreach ($group in $var.Name) {
    Add-ADGroupMember -Identity $group -Member TestUser
}

The issues with your attempt was that you never provided a property name but rather just did the calculation. In the loop, you needed to access just the calculated values rather than the object that contained a property with the values.


If the goal is to read a user list from a file and then update each user's membership, you may do the following:

foreach ($user in (Get-Content c:\userlist.txt)) {
    $var = Get-ADUser -Identity $user -Properties memberof |
               Select-Object -ExpandProperty memberof |
                   Where {$_ -match "CN=DFS*"} |
                       Get-ADGroup -Properties name |
                           Select-Object @{Label='Name';Expression={"MW-"+ $_.name}}

    Add-ADPrincipalGroupMembership -Identity $user -MemberOf $var.Name
}

Using a foreach loop allows for assigning each user to a variable as you iterate through the list. That variable can then be referenced at any point within the loop.

Upvotes: 1

Related Questions