1

Consider this situation. I have multiple domains and am writing a script that covers all domains to add users to groups. I'd like to do soemthing like this:

# UserID selected earlier in the script
$SelectedUID = "testuser"
# These could contain any number of groups, or none at all
$CommonGroupsDomain1 = "Group1", "Group2"
$CommonGroupsDomain2 = "GroupX", "GroupY"
$CommonGroupsDomain3 = $null

# The current domain (selected earlier in the script)
$CurrentDomain = "Domain1"

If (($"CommonGroups$CurrentDomain")) {
    ($"CommonGroups$CurrentDomain") | ForEach-Object {
        Add-ADGroupMember -Identity $_ -Members $SelectedUser -Server $CurrentDomainController 
    }
}
Else {
    "No common groups for this domain"
}

So, for $CommonGroups$CurrentDomain is it possible to tell PS to treat that string addition as the object name?

Here's an alternative way of doing things, but seems a bit clunky:

$CommonGroups = $null
Switch ($CurrentDomain) {
    'Domain1' {
        $CommonGroups = $CommonGroupsDomain1
    }
    'Domain2' {
        $CommonGroups = $CommonGroupsDomain2
    }
    'Domain3' {
        $CommonGroups = $CommonGroupsDomain3   
    }
}

If ($CommonGroups) {
         Add-ADGroupMember -Identity $_ -Members $SelectedUser -Server $CurrentDomainController
     }
}
Scepticalist
  • 3,737
  • 1
  • 13
  • 30

1 Answers1

1

This code allows you to do what you want. The third line below would be in your if statment.

$CommonGroupsDomain1 = "Group1", "Group2"

$CurrentDomain = "Domain1"

Get-Variable -Name "CommonGroups$CurrentDomain" -ValueOnly 
derekbaker783
  • 8,109
  • 4
  • 36
  • 50