获取用于通过 Azure、AWS 或 GCP 市场注册 Microsoft Entra 专用网络连接器的身份验证令牌

概述

PowerShell 脚本可帮助你获取用于通过 Azure 市场AWS 市场GCP 市场注册 Microsoft Entra 专用网络连接器的身份验证令牌。

如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

注意

建议使用 Azure Az PowerShell 模块与 Azure 交互。 请参阅安装 Azure PowerShell 以开始使用。 若要了解如何迁移到 Az PowerShell 模块,请参阅 将 Azure PowerShell 从 AzureRM 迁移到 Az

此示例需要 Microsoft Graph Beta PowerShell 模块 2.10 或更高版本。

重要注意事项

  • 从提升的 PowerShell ISE 以管理员身份运行 PowerShell 脚本。
  • 不要在已安装专用网络连接器的 Windows 计算机上运行脚本。
  • 请确保计算机上没有 C:\temp 文件夹。 如果您有一些文件存储在C:\temp文件夹中,请在运行脚本之前移动这些文件。
  • 脚本成功运行后,访问令牌在以下位置 C:\token.txt可用。

示例脚本

# This sample script lets you obtain the Auth Token that you can use for registering the Entra private network connector through Marketplace.
#
# Version 1.2
#
# This script requires following 
#    - PowerShell 5.1 (x64) or beyond
#    - Module: MicrosoftEntraPrivateNetworkConnectorPSModule 
#
# The script will get the module as result of Entra Private Network Connector Installation and quiet Registration (/q flag). A quiet installation doesn't prompt you to accept the End-User License Agreement.
# This script will uninstall the Entra Private Network Connector once the required modules are downloaded. 
#
# Before you begin:
#    
# - Make sure you are running PowerShell as an Administrator
# - You are on Windows Machine which is not running the Entra Private Network Connector already. If you already have a connector installed, quiet registration step below will fail. 
# - Make sure there is no C:\temp folder on the machine. If you have some files stored, please move those before running the script 

# Make sure ExecutionPolicy is set to Unrestricted
Set-ExecutionPolicy UnRestricted -Force

# The script will use a temp folder on C Drive. First it will remove the folder and create a new folder to ensure its empty.
$tempPath = "C:\temp"
$tokenPath = "C:\token.txt"

# Check if the folder exists
if (Test-Path -Path $tempPath) {
    Write-Host "Your C Drive has existing temp folder that is being deleted"
    Remove-Item -Path $tempPath -Recurse -Force
} 

# Creating C:\temp folder
New-Item -ItemType Directory -Path $tempPath -Force | Out-Null

# Copy Required Dlls 
Write-Host "Downloading Entra Private Network Connector Installer..."
Invoke-WebRequest https://download.msappproxy.net/Subscription/d3c8b69d-6bf7-42be-a529-3fe9c2e70c90/Connector/DownloadConnectorInstaller -OutFile "$tempPath\MicrosoftEntraPrivateNetworkConnectorInstaller.exe"

# Set the prompt path to C:\temp
Set-Location -Path $tempPath

# Quiet Registration of the Connector. This step will provide the required Module for acquiring the token. 
# At the end of this step, you should see 2 folders under C:\Program Files. 1) Microsoft Entra private network connector 2) Microsoft Entra private network connector updater
# These folders contains the required modules needed for getting the token. 
Write-Host "Installing connector (quiet mode)..."
Start-Process -FilePath ".\MicrosoftEntraPrivateNetworkConnectorInstaller.exe" -ArgumentList "REGISTERCONNECTOR=`"false`"", "/q" -Wait

# Wait 60 seconds for installation to complete
Write-Host "Waiting for installation to complete..."
Start-Sleep -Seconds 60

$folderPath = "C:\Program Files\Microsoft Entra private network connector\Modules\MicrosoftEntraPrivateNetworkConnectorPSModule"

# Check if the Module exists
if (Test-Path -Path $folderPath) {
    Write-Host "The Module is successfully made available at path: $folderPath"
    
    # Set the prompt path to C:\Program Files\Microsoft Entra private network connector\Modules\MicrosoftEntraPrivateNetworkConnectorPSModule
    Set-Location -Path "C:\Program Files\Microsoft Entra private network connector\Modules\MicrosoftEntraPrivateNetworkConnectorPSModule"

    # Import Module 
    Import-Module ..\MicrosoftEntraPrivateNetworkConnectorPSModule -ErrorAction Stop

    # Load MSAL  
    Add-Type -Path .\Microsoft.Identity.Client.dll

    # The AAD authentication endpoint uri
    $authority = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"

    # The application ID of the connector in AAD. Use the Connector AppId below
    $connectorAppId = "55747057-9b5d-4bd4-b387-abf52a8bd489"

    # The AppIdUri of the registration service in AAD
    $registrationServiceAppIdUri = "https://proxy.cloudwebappproxy.net/registerapp/user_impersonation"

    # Define the resources and scopes you want to call
    $scopes = New-Object System.Collections.ObjectModel.Collection["string"]
    $scopes.Add($registrationServiceAppIdUri)

    $app = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($connectorAppId).WithAuthority($authority).WithDefaultRedirectUri().Build()

    [Microsoft.Identity.Client.IAccount] $account = $null

    # Acquiring the token
    Write-Host "Acquiring authentication token (interactive login required)..."
    $authResult = $null
    $authResult = $app.AcquireTokenInteractive($scopes).WithAccount($account).ExecuteAsync().ConfigureAwait($false).GetAwaiter().GetResult()

    # Check AuthN result
    If (($authResult) -and ($authResult.AccessToken) -and ($authResult.TenantId)) {
        $token = $authResult.AccessToken
        $tenantId = $authResult.TenantId
        
        $accessToken = $token

        New-Item -ItemType File -Path $tokenPath -Force | Out-Null
        Set-Content -Path $tokenPath -Value "$accessToken"
        
        Write-Host "Token successfully acquired and saved to $tokenPath"

        # Set the prompt path to C: 
        Set-Location -Path "C:\"

        # Uninstall the Connector from your machine.
        # You can do so programmatically (below) or manually by double clicking C:\temp\MicrosoftEntraPrivateNetworkConnectorInstaller.exe and choose Uninstall. 
        # Note that if the Connector service is not uninstalled properly, next iteration can fail on this machine.
        Write-Host "Uninstalling connector..."
        Start-Process -FilePath "$tempPath\MicrosoftEntraPrivateNetworkConnectorInstaller.exe" -ArgumentList "/uninstall", "/quiet" -Wait

        # Wait 60 seconds
        Write-Host "Waiting for uninstallation to complete..."
        Start-Sleep -Seconds 60

        # Delete the related files
        Write-Host "Cleaning up files..."
        if (Test-Path -Path $tempPath) {
            try {
                Remove-Item -Path $tempPath -Recurse -Force
            } catch {
                Write-Warning "Could not fully remove '$tempPath': $_"
            }
        }
        if (Test-Path -Path "C:\Program Files\Microsoft Entra private network connector") {
            try {
                Remove-Item -Path "C:\Program Files\Microsoft Entra private network connector" -Recurse -Force
            } catch {
                Write-Warning "Could not fully remove 'Microsoft Entra private network connector' folder: $_"
            }
        }
        if (Test-Path -Path "C:\Program Files\Microsoft Entra private network connector updater") {
            try {
                Remove-Item -Path "C:\Program Files\Microsoft Entra private network connector updater" -Recurse -Force
            } catch {
                Write-Warning "Could not fully remove 'Microsoft Entra private network connector updater' folder: $_"
            }
        }

        Write-Output "Access Token that you acquired is available in $tokenPath."
        Write-Output "Please ensure no additional spaces are introduced when copying token to marketplace input form. Introducing spaces can change the token and can cause failures"

    }
    else {
        Write-Error "Authentication failed: result, access token, or tenant ID was null. No token has been saved. Please re-run the script and complete the interactive login."
        Set-Location -Path "C:\"
        return
    }

else {
    Write-Host "The required module is not made available at path: $folderPath"
    Write-Host "This could be related to left over state from previous installation of connector on this machine."
    Write-Host "You can try to go to c:\temp\ and double click the MicrosoftEntraPrivateNetworkConnectorInstaller.exe file. Click Uninstall if visible. This can clean the state."
    Write-Host "If you don't have .exe file, you can download it from https://download.msappproxy.net/Subscription/d3c8b69d-6bf7-42be-a529-3fe9c2e70c90/Connector/DownloadConnectorInstaller and double click it to Uninstall"
    Write-Host "Try Again after the state is clean"
    return
}

后续步骤