powershell calculated property inserting variable before calculation

I have been trying for some time now, to get my $Tenant.Name variable to get inserted as text, instead of as a variable to be grabbed later.

Currently I receive the following output:

Tenant 1 - AADRoles Tenant1 - Groups Tenant 2 - AADRoles Tenant 2 - Groups
Tenant2Administrator Tenant2AdminGroup Tenant2Administrator Tenant2AdminGroup

Both Tenants are getting the roles and groups from Tenant 2, which I guess is because the Calculated Property isn't calculating until the end, where it will then use the last value. Am I just a idiot for doing it this way?

The SubTenantUsers and MainTenantUsers variables contains information from Get-AzureADUser, Get-AzureADDirectoryRole and Get-AzureADGroup to help figure out which groups and roles the individual users are assigned.

# Get a list of tenants the user has access to
$Tenants = Get-AzTenant | Where-Object {$_.TenantId -NotMatch $TenantId}

# Get user Roles in other tenants
foreach ($Tenant in $Tenants) {

    $null = Connect-AzureAD -TenantId $Tenant.Id

    $SubTenantUsers = Get-TenantUsersRolesAndGroups

    foreach ($MainTenantUser in $MainTenantUsers) {
        ### Add tenant to list of tenants the user is a member of
        if ($SubTenantUsers.UserPrincipalName -like ('{0}*' -f $MainTenantUser.UserPrincipalName.Replace("@", "_"))) {
            $MainTenantUser.AccessibleTenants += $Tenant.Name

        ### Add the users roles and groups in the tenant
        $null = Add-Member -InputObject $MainTenantUser -MemberType 'NoteProperty' -Name $Tenant.Name -Force -Value (
                Roles   = ($SubTenantUsers | Where-Object UserPrincipalName -like ('{0}*' -f $MainTenantUser.UserPrincipalName.Replace("@", "_")) | Select-Object Roles).Roles
                Groups  = ($SubTenantUsers | Where-Object UserPrincipalName -like ('{0}*' -f $MainTenantUser.UserPrincipalName.Replace("@", "_")) | Select-Object Groups).Groups

foreach ($Tenant in $Tenants) {
    $properties += @{
        Name = "$($Tenant.Name) - AADRoles"
        Expression = {($_.($Tenant.Name).'Roles'.'DisplayName' | Sort-Object) -join ', '}
    $properties += @{
        Name = "$($Tenant.Name) - Groups"
        Expression = {($_.($Tenant.Name).'Groups'.'DisplayName' | Sort-Object) -join ', '}

$MainTenantUsers | Sort-Object 'DisplayName' | Select-Object $properties |
    Export-Csv -Path "$pathto\output.csv" -Encoding 'UTF8' -NoTypeInformation

Read more here: https://stackoverflow.com/questions/67938466/powershell-calculated-property-inserting-variable-before-calculation

Content Attribution

This content was originally published by djandDK at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: