简体   繁体   中英

How to use <New-Object -TypeName psobject -Property> to gather info on 2 foreach

I need to aggregate the results of 2 foreach so I can run a nice report - this is the script:

$users = Get-ADGroupMember -Identity 'TESTGRoup'
$result1 = ForEach ($user in $users){

    New-Object -TypeName psobject -Property @{
        User   = $user
        CN     = $User.SamAccountName
        Domain = $user.name
        Name   = $user.SID
    }
}

$Result4 = Get-ADGroupMember 'TESTGRoup' |
    Where-Object {$_.objectClass -eq 'User'} |
    Get-AdUser |
    ForEach {
        Get-MsolUser -UserPrincipalName $_.UserPrincipalName | Select UserprincipalName, Blockcredential  
        $result7 = New-Object -TypeName psobject -Property @{
            User1   = $Result4.UserPrincipalName
            CN1     = $Result4.BlockCredential
        }
    }

The end result is all the users joined up on a single line and not on a table.

Sorry for the code format - not sure how to present it better.

Thanks

If I understand your question correctly, the below code will generate objects with the aggregated data you need on a single object per user:

#requires -Version 3
$results = foreach ($user in Get-ADGroupMember -Identity 'TESTGRoup')
{
    $user | ? objectClass -eq User | Get-ADUser | % {
        $msol = Get-MsolUser -UserPrincipalName $PSItem.UserPrincipalName

        [pscustomobject]@{
            'User'   = $user
            'CN'     = $user.SamAccountName
            'Domain' = $user.Name
            'Name'   = $user.SID
            'User1'  = $msol.UserPrincipalName
            'CN1'    = $msol.BlockCredential
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM