Powershell - 获取列表成员值

Powershell - Getting list member value

在下面的代码片段中,我尝试将外部列表 $admin_roles 中的 $roleName(作为角色)附加到文件中。 该角色总是显示为空(其他列都可以)。我错过了什么?

Connect-MsolService
$output_file_location = "c:\temp\azure_admins_mfa_status_"+$(get-date -f yyyy-MM-dd-HH-mm-ss)+".csv"
$admin_roles = "Company Administrator","Billing Administrator","Conditional Access Administrator","Exchange Service administrator","Helpdesk administrator","Password administrator","Security administrator","Sharepoint Service administrator"

# Gets all the members in the admin roles in the roles list above
# Gets the MFA status for each member
# Appends the below data points to a file specified in the $output_file_location variable 
# DisplayName,E-mail,Role,MFA-Requirements, MFA-Methods, MFA-MethodsDefault
function get-mfa-status
{
    foreach ($roleName in $admin_roles)
    {
        write-output $roleName
        $members = Get-MsolRoleMember -RoleObjectId $(Get-MsolRole -RoleName $roleName).ObjectId
        #write-output $members
        foreach ($member in $members) 
        {
            write-output $member.EmailAddress
            
        }
        
        foreach ($member in $members) 
        { 
        Get-MsolUser -UserPrincipalName $member.EmailAddress | select DisplayName, `
        @{N='E-mail';E={$_.userPrincipalName}}, `
        {N='Role';E={$roleName}}, `
        @{N='MFA-Requirements';E={(($_).StrongAuthenticationRequirements.state)}}, `
        @{N='MFA-Methods';E={(($_).StrongAuthenticationMethods.MethodType)}}, `
        @{N='MFA-MethodsDefault';E={($_.StrongAuthenticationMethods | where isdefault -eq 'true').MethodType}} `
        | select DisplayName,E-mail,Role,MFA-Requirements, MFA-Methods, MFA-MethodsDefault| Export-Csv $output_file_location -Append `
        }
        
    }
    
    
}

您的代码 @{N='Role';E={$roleName}} 之前缺失。通常,您会立即注意到这一点,因为它会将列名称显示为整个表达式。

但是,由于第二个 Select-Object,您没有看到。 PowerShell 选择名为 Role 的列。由于它不存在,您会看到空列。

旁注:我认为第二个 Select-Object 没有必要。跳过它会产生相同的输出(前提是您如上所述更正了损坏的表达式)。