如何在 PowerShell 中使用 Get-MgGroup

Jacki

Microsoft Graph PowerShell 中的 Get-MgGroup cmdlet 檢索 Microsoft Entra ID 中的所有組詳細信息。您可以獲取組織中的所有 Microsoft 365 組或特定組。雖然您可以獲取 Microsoft Entra 管理中心或 Microsoft 365 管理中心中的所有組,但您始終可以使用 PowerShell 執行更多且精確的操作。在本文中,您將了解如何在 PowerShell 中使用 Get-MgGroup cmdlet。

開始之前

在繼續操作之前,請務必安裝並連接到 Microsoft Graph PowerShell。否則,Get-MgGroup cmdlet 將不起作用。

安裝 Microsoft Graph PowerShell

以管理員身份運行 PowerShell 並安裝 Microsoft Graph PowerShell 模塊。

Install-Module Microsoft.Graph -Force

重要的:在運行 cmdlet 或腳本之前,請務必更新到最新的 Microsoft Graph PowerShell 模塊版本,以防止出現錯誤和不正確的結果。

連接到 Microsoft Graph PowerShell

您需要使用正確的權限連接到 Microsoft Graph PowerShell。如果不這樣做,則無法使用 Get-MgGroup cmdlet 檢索組結果。

Connect-MgGraph -Scopes "Group.Read.All"

您是否希望在沒有用戶交互的情況下進行連接,因為您希望腳本自動運行?使用基於證書的身份驗證或客戶端密鑰進行設置。請閱讀連接到 Microsoft Graph PowerShell 一文來了解更多信息。

獲取群組信息

我們首先從基礎開始,那就是獲取群組信息。

獲取單組信息

要獲取組信息,請使用-組ID參數並附加組 ID。

Get-MgGroup -GroupId "14603c19-0afa-4f2f-9c13-64d25eedfca3"

您還可以使用-篩選參數來搜索 DisplayName 以獲取組信息。

Get-MgGroup -Filter "DisplayName eq 'Group1'"

添加格式列表cmdlet 獲取屬性列表。

Get-MgGroup -Filter "DisplayName eq 'Group1'" | Format-List

獲取所有群組信息

運行 Get-MgGroup cmdlet,包括-全部參數,檢索所有組。

筆記:始終使用-全部參數來獲取所有結果。否則,只會出現 100 個項目。

Get-MgGroup -All

為了計算所有組的數量,我們將添加測量對象cmdlet 到命令。

Get-MgGroup -All | Measure-Object | Select-Object -ExpandProperty Count

另一種計算所有組的方法。

(Get-MgGroup -All).Count

獲取空組

查找所有沒有分配成員的組。

Get-MgGroup -All | Where-Object { (Get-MgGroupMember -GroupId $_.Id).Count -eq 0 } | Sort-Object DisplayName

要獲取所有組及其組類型,請使用文章中的 PowerShell 腳本如何使用 PowerShell 在 Microsoft 365 中查找空組

獲取所有云組

如果您有混合環境,組將從本地 AD 同步到 Microsoft Entra ID。本地 AD 是您的域權限,您應該在那裡創建組。但是,組織中可能存在直接在雲中創建的組。

我們僅過濾雲組並按顯示名稱對它們進行排序。

閱讀更多:修復:開始菜單中缺少 Windows PowerShell

Get-MgGroup -All -Filter "OnPremisesSyncEnabled ne true" -ConsistencyLevel eventual -CountVariable CountVar | Sort-Object DisplayName

獲取本地同步組

僅獲取同步到雲的本地組並按顯示名稱對它們進行排序。

Get-MgGroup -All -Filter "OnPremisesSyncEnabled eq true" -ConsistencyLevel eventual -CountVariable CountVar | Sort-Object DisplayName

獲取群組的所有者

要了解哪個所有者分配給哪個組,我們可以獲取所有組及其所有者的列表。您必須使用 Get-MgGroup 和 Get-MgGroupOwner cmdlet 來檢索成員。

讓我們將所有組(包括其所有者)導出到 CSV 文件。填寫 CSV 路徑4號線

Connect-MgGraph -Scopes "Group.Read.All", "Directory.Read.All" -NoWelcome

# Define the CSV file path
$csvPath = "C:tempGroupOwners.csv"

# Get all groups
$Groups = Get-MgGroup -All
$TotalGroups = $Groups.Count
$ProgressCounter = 0

$Report = [System.Collections.Generic.List[Object]]::new()

# Loop through each group
foreach ($Group in $Groups) {
    $ProgressCounter++
    $Percentage = [Math]::Round(($ProgressCounter / $TotalGroups) * 100, 2)
    Write-Progress -Activity "Processing Groups - $Percentage%" -Status "Checking owners for $($Group.DisplayName)" -PercentComplete $Percentage

    $Owners = Get-MgGroupOwner -GroupId $Group.Id -All | Select-Object -ExpandProperty AdditionalProperties
    if ($Owners) {
        foreach ($Owner in $Owners) {
            $OwnerType = switch ($Owner.'@odata.type') {
                "#microsoft.graph.user" { "User" }
                "#microsoft.graph.group" { "Group" }
                "#microsoft.graph.servicePrincipal" { "Service Principal" }
                "#microsoft.graph.device" { "Device" }
                "#microsoft.graph.orgContact" { "Contact" }
                default { "Unknown" }
            }
            $ReportLine = [PSCustomObject]@{
                GroupName              = $Group.DisplayName
                OwnerName              = $Owner.displayName
                OwnerEmail             = $Owner.mail
                OwnerUserPrincipalName = $Owner.userPrincipalName
                OwnerType              = $OwnerType
            }
            $Report.Add($ReportLine)
        }
    }
    else {
        $ReportLine = [PSCustomObject]@{
            GroupName              = $Group.DisplayName
            OwnerName              = ""
            OwnerEmail             = ""
            OwnerUserPrincipalName = ""
            OwnerType              = ""
        }
        $Report.Add($ReportLine)
    }
}

# Complete the progress bar
Write-Progress -Activity "Processing Groups" -Status "Completed" -PercentComplete 100 -Completed

# Export the report to CSV
$Report | Sort-Object GroupName | Export-Csv -Path $csvPath -NoTypeInformation -Encoding utf8
Write-Host "Report exported to $csvPath" -ForegroundColor Cyan

這就是 CSV 文件報告的樣子。

閱讀更多關於如何在 PowerShell 中使用 Get-MgGroupOwner

獲取群組成員

要知道哪個成員被分配到哪個組,我們可以獲取所有組及其成員的列表。您必須使用 Get-MgGroup 和 Get-MgGroupMember cmdlet 來檢索成員。

讓我們將所有組(包括其成員)導出到 CSV 文件。填寫 CSV 路徑4號線

Connect-MgGraph -Scopes "Group.Read.All", "Directory.Read.All" -NoWelcome

# Define the CSV file path
$csvPath = "C:tempGroupMembers.csv"

# Get all groups
$Groups = Get-MgGroup -All
$TotalGroups = $Groups.Count
$ProgressCounter = 0

$Report = [System.Collections.Generic.List[Object]]::new()

# Loop through each group
foreach ($Group in $Groups) {
    $ProgressCounter++
    $Percentage = [Math]::Round(($ProgressCounter / $TotalGroups) * 100, 2)
    Write-Progress -Activity "Processing Groups - $Percentage%" -Status "Checking members for $($Group.DisplayName)" -PercentComplete $Percentage

    $Members = Get-MgGroupMember -GroupId $Group.Id -All | Select-Object -ExpandProperty AdditionalProperties
    if ($Members) {
        foreach ($Member in $Members) {
            $memberType = switch ($Member.'@odata.type') {
                "#microsoft.graph.user" { "User" }
                "#microsoft.graph.group" { "Group" }
                "#microsoft.graph.servicePrincipal" { "Service Principal" }
                "#microsoft.graph.device" { "Device" }
                "#microsoft.graph.orgContact" { "Contact" }
                default { "Unknown" }
            }
            $ReportLine = [PSCustomObject]@{
                GroupName               = $Group.DisplayName
                MemberName              = $Member.displayName
                MemberEmail             = $Member.mail
                MemberUserPrincipalName = $Member.userPrincipalName
                MemberType              = $memberType
            }
            $Report.Add($ReportLine)
        }
    }
    else {
        $ReportLine = [PSCustomObject]@{
            GroupName               = $Group.DisplayName
            MemberName              = ""
            MemberEmail             = ""
            MemberUserPrincipalName = ""
            MemberType              = ""
        }
        $Report.Add($ReportLine)
    }
}

# Complete the progress bar
Write-Progress -Activity "Processing Groups" -Status "Completed" -PercentComplete 100 -Completed

# Export the report to CSV
$Report | Sort-Object GroupName | Export-Csv -Path $csvPath -NoTypeInformation -Encoding utf8
Write-Host "Report exported to $csvPath" -ForegroundColor Cyan

這就是 CSV 文件報告的樣子。

閱讀更多關於如何在 PowerShell 中使用 Get-MgGroupMember

獲取以顯示名稱開頭的組

我們可以添加開始於運算符並檢索以顯示名稱開頭的所有結果。

Get-MgGroup -All -Filter "startsWith(DisplayName,'Sales')"

您還可以添加字母而不是單詞。

Get-MgGroup -All -Filter "startsWith(DisplayName,'S')"

獲取以郵件地址結尾的組

添加結束於運算符檢索以特定郵件地址結尾的所有組並按顯示名稱對它們進行排序。

Get-MgGroup -All -Filter "endsWith(mail,'exoip.com')" -Sort "displayName" -ConsistencyLevel eventual -CountVariable CountVar

搜索以特定郵件地址結尾的兩個域。

Get-MgGroup -All -Filter "endsWith(mail,'exoip.com') or endsWith(mail,'tajran.com')" -Sort "displayName" -ConsistencyLevel eventual -CountVariable CountVar

獲取創建日期的群組

獲取單個組的創建日期。

Get-MgGroup -GroupId "14603c19-0afa-4f2f-9c13-64d25eedfca3" | Select-Object DisplayName, CreatedDateTime

獲取所有組的創建日期。

Get-MgGroup -All | Select-Object DisplayName, CreatedDateTime | Sort-Object CreatedDateTime

讓我們獲取 2024 年創建的所有組。

Get-MgGroup -All -Filter ("CreatedDateTime ge " + (Get-Date "2024-01-01T00:00:00Z").ToString("yyyy-MM-ddTHH:mm:ssZ") + " and CreatedDateTime le " + (Get-Date "2024-12-31T23:59:59Z").ToString("yyyy-MM-ddTHH:mm:ssZ")) -ConsistencyLevel eventual -CountVariable Count

了解如何在 PowerShell 腳本中添加 Get-MgGroup cmdlet 的一個極好方法是查看 PowerShell 腳本示例:

  • 檢查 Microsoft 365 用戶許可證是直接分配還是從組繼承
  • 刪除為具有組許可證的用戶直接分配的許可證
  • 使用 PowerShell 將 Microsoft 365 組成員導出到 CSV

結論

您學習瞭如何在 PowerShell 中使用 Get-MgGroup。 Get-MgGroup cmdlet 是一個出色的 cmdlet,用於從 Microsoft Entra ID 和 Microsoft 365 檢索組。使用特定參數或將它們組合起來,根據您希望結果的顯示方式篩選搜索結果。

您喜歡這篇文章嗎?您可能還喜歡使用 PowerShell 從 CSV 創建 Microsoft Entra ID 用戶。不要忘記關注我們並分享這篇文章。