使用 PowerShell 導出條件訪問命名位置

Jacki

Microsoft Entra 條件訪問策略使用命名位置,它們非常棒!您可以在策略中排除或包含指定位置。但是,您想要一份命名位置報告並仔細查看它。在本文中,您將了解如何使用 PowerShell 導出條件訪問命名位置。

在 Microsoft Entra 管理中心查找命名位置

要查找 Microsoft Entra ID 中的所有命名位置,請按照下列步驟操作:

  1. 登錄到微軟 Entra 管理中心
  2. 導航至保護 > 條件訪問 > 命名位置

單擊“命名位置”列表來查看設置了哪些 IP 地址或選擇了哪些國家/地區需要花費時間並且不易查看。因此,最好使用 PowerShell 創建命名位置報告。

安裝 Microsoft Graph PowerShell

在我們進一步繼續並從 Microsoft Entra 租戶獲取所有命名位置之前,我們需要安裝 Microsoft Graph PowerShell。

以管理員身份啟動 Windows PowerShell 並運行以下命令。

Install-Module Microsoft.Graph -Force

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

現在我們已經安裝了 Microsoft Graph PowerShell SDK 模塊,我們可以進入下一步。

連接到 Microsoft Graph PowerShell

您需要使用正確的權限連接到 Microsoft Graph PowerShell。

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

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

要使用 PowerShell 獲取條件訪問中的命名位置,請使用獲取 MgIdentityConditionalAccessNamedLocationcmdlet。

Get-MgIdentityConditionalAccessNamedLocation -All

輸出顯示命名位置。但是,它沒有顯示我們需要的重要屬性。

Id                                   CreatedDateTime     DisplayName      ModifiedDateTime
--                                   ---------------     -----------      ----------------
0573aebb-3e9f-43c0-ba79-10b433d44dda 13/01/2025 09:05:51 Head Office      13/01/2025 09:05:51
0f3bbcc0-4920-42cd-8760-8bdc03980d5f 13/01/2025 09:06:47 Branch Office    13/01/2025 09:46:29
06af1569-60fd-4c54-85b0-9f2d59fc2803 13/01/2025 09:49:38 Trusted Location 13/01/2025 09:49:38
1837e1bf-ee5e-4cec-9a57-775ce18722c4 13/01/2025 09:55:59 NL               13/01/2025 10:35:28
1f9d9e0a-5195-4822-ba6b-d3b07ed54088 13/01/2025 10:35:56 USA + France     14/01/2025 09:20:41

我們缺少許多屬性,因此我們將創建一個腳本來導出包含所有基本信息的精美報告。

使用 PowerShell 導出條件訪問命名位置

Export-NamedLocations.ps1 PowerShell 腳本將獲取 Microsoft Entra 租戶中的所有條件訪問命名位置及其關聯策略。之後,它將報告導出到 CSV 文件。您可以使用 Microsoft Excel 或支持 CSV 文件擴展名的任何其他應用程序打開 CSV 文件。

對於每個指定位置,它都會收集以下信息:

  1. 顯示名稱
  2. 位置類型
  3. 值得信賴
  4. IP範圍
  5. 國家
  6. 國家查找方法
  7. 包括未知國家和地區
  8. 創建日期
  9. 修改日期時間
  10. 政策

要使用 PowerShell 導出 Microsoft Entra ID 中的所有命名位置,請按照以下步驟操作:

步驟 1. 準備 Export-NamedLocations PowerShell 腳本

上創建兩個文件夾(中:)駕駛:

  • 溫度
  • 腳本

下載 Export-NamedLocations.ps1 PowerShell 腳本並將其放置在C:腳本文件夾。該腳本會將 JSON 文件導出到C:溫度文件夾。

確保文件未被阻止,以防止運行腳本時出現錯誤。請閱讀文章運行 PowerShell 腳本時出現未數字簽名錯誤來了解更多信息。

另一種選擇是將以下代碼複製並粘貼到記事本中。給它起個名字導出命名位置.ps1並將其放置在C:腳本文件夾。

<#
    .SYNOPSIS
    Export-NamedLocations.ps1

    .DESCRIPTION
    Export Conditional Access Named Locations policies to CSV file.

    .LINK
    www.alitajran.com/export-conditional-access-named-locations-powershell/

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran
    X:          x.com/alitajran

    .CHANGELOG
    V1.00, 01/13/2025 - Initial version
#>

param (
    [string]$CSVPath = "C:tempNamedLocations.csv"
)

# Connect to Microsoft Graph with specific scopes
Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome

# Retrieve all Conditional Access Named Locations
$locations = Get-MgIdentityConditionalAccessNamedLocation -All | Select-Object Id, DisplayName, AdditionalProperties, CreatedDateTime, ModifiedDateTime

# Check if any Named Locations are found
if (-not $locations) {
    Write-Host "No Named Locations found in Microsoft Entra ID." -ForegroundColor Cyan
    exit
}

# Retrieve all Conditional Access Policies
$CAPolicy = Get-MgIdentityConditionalAccessPolicy -All | Select-Object Id, DisplayName, Conditions

# Initialize a new list to store report data
$Report = [System.Collections.Generic.List[Object]]::new()

# Get all specific cultures and store them in $cultures
$cultures = [System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::SpecificCultures)

# Create a dictionary for country code to full country name mapping
$countryNames = @{}
foreach ($culture in $cultures) {
    $region = [System.Globalization.RegionInfo]::new($culture.Name)
    if (-not $countryNames.ContainsKey($region.TwoLetterISORegionName)) {
        $countryNames[$region.TwoLetterISORegionName] = $region.EnglishName
    }
}

# Process the Named Locations
foreach ($location in $locations) {
    # Determine the type of location (IP Ranges or Countries)
    $locationType = if ($location.AdditionalProperties.ipRanges) { "IP Ranges" } else { "Countries" }

    # Prepare list to hold country names
    $countries = [System.Collections.Generic.List[string]]::new()
    foreach ($countryCode in $location.AdditionalProperties.countriesAndRegions) {
        if ($countryNames.ContainsKey($countryCode)) {
            $countries.Add($countryNames[$countryCode])
        }
        else {
            $countries.Add($countryCode)
        }
    }

    # Translate country lookup method to a more descriptive string
    $countryLookupMethod = switch ($location.AdditionalProperties.countryLookupMethod) {
        "authenticatorAppGps" { "Determine location by GPS coordinates" }
        "clientIpAddress" { "Determine location by IP address (IPv4 and IPv6)" }
        default { $location.AdditionalProperties.countryLookupMethod }
    }

    # Check which policies include or exclude this Named Location
    $policies = [System.Collections.Generic.List[string]]::new()
    foreach ($Policy in $CAPolicy) {
        $InclLocation = $Policy.Conditions.Locations.IncludeLocations
        $ExclLocation = $Policy.Conditions.Locations.ExcludeLocations
        if ($InclLocation -contains $location.Id -or $ExclLocation -contains $location.Id) {
            $policies.Add($Policy.DisplayName)
        }
    }

    # Create a custom object for each Named Location with all relevant details including policy names
    $ReportLine = [PSCustomObject][Ordered]@{
        DisplayName                       = $location.DisplayName
        LocationType                      = $locationType
        IsTrusted                         = $location.AdditionalProperties.isTrusted
        IPranges                          = ($location.AdditionalProperties.ipRanges.cidrAddress -join ',')
        Countries                         = ($countries -join ',')
        CountryLookupMethod               = $countryLookupMethod
        IncludeUnknownCountriesAndRegions = $location.AdditionalProperties.includeUnknownCountriesAndRegions
        CreatedDate                       = $location.CreatedDateTime
        ModifiedDateTime                  = $location.ModifiedDateTime
        Policy                            = ($policies -join ',')
    }
    $Report.Add($ReportLine)
}

# Sort the report by the DisplayName
$SortedReport = $Report | Sort-Object DisplayName

# Display report in a grid view
$SortedReport | Out-GridView -Title "Conditional Access Named Locations"

# Export the sorted report to a CSV file
$SortedReport | Export-Csv -Path $CSVPath -NoTypeInformation -Encoding utf8
Write-Host "File exported to: $CSVPath" -ForegroundColor Cyan

這就是它的樣子。

步驟 2. 運行 Export-NamedLocations PowerShell 腳本

運行導出命名位置.ps1用於獲取所有條件訪問命名位置並將其導出到臨時文件夾中的 CSV 文件的 PowerShell 腳本。

有關的:如何使用 PowerShell 導出 MS Teams 聊天歷史記錄

C:scripts.Export-NamedLocations.ps1 -CSVPath "C:tempNamedLocations.csv"

報告輸出將發送到單獨窗口 (Out-GridView) 中的交互式表格。

步驟 3. 檢查指定位置 CSV 文件報告

導出命名位置.ps1PowerShell 腳本會將所有命名位置導出到 CSV 文件。在路徑中找到CSV文件C:溫度

打開命名位置.csv包含您最喜歡的應用程序的 CSV 文件。例如,微軟 Excel。

條件訪問命名位置報告看起來非常好。

就是這樣!

結論

您了解瞭如何使用 PowerShell 導出 Microsoft Entra ID 中的條件訪問命名位置。首先,連接到 Microsoft Graph PowerShell 並運行 Export-NamedLocations.ps1 PowerShell 腳本。之後,所有命名位置屬性都可以在 CSV 文件中使用。

您喜歡這篇文章嗎?您可能還喜歡如何配置 Microsoft Entra 多重身份驗證。不要忘記關注我們並分享這篇文章。