You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure租户证书认证脚本报错:New-AzADServicePrincipal参数集无法解析

解决New-AzADServicePrincipal参数集错误及关联资源组/订阅的方法

一、修复参数集解析错误

错误根源是New-AzADServicePrincipal命令使用了不存在的参数-StartDate和-EndDate,对应的证书有效期参数应为-CertStartDate和-CertEndDate。修正后的命令如下:

$sp = New-AzADServicePrincipal -AppId $applicationId -CertValue $keyValue -CertStartDate $cert.NotBefore -CertEndDate $cert.NotAfter

说明:-AppId是-ApplicationId的别名,两者通用,但必须搭配正确的证书有效期参数名,否则会触发参数集不匹配的报错。

二、为应用注册关联资源组/订阅

应用注册本身无需直接关联资源组或订阅,需通过给其对应的服务主体分配RBAC角色来授予资源访问权限,具体操作如下:

1. 关联订阅(授予订阅级权限)

# 替换为你的目标订阅ID
$subscriptionId = "your-subscription-id"
# 分配Reader角色(可按需替换为Contributor、Owner等角色)
New-AzRoleAssignment -ServicePrincipalName $applicationId `
                     -RoleDefinitionName "Reader" `
                     -Scope "/subscriptions/$subscriptionId"

2. 关联资源组(授予资源组级权限)

# 替换为你的订阅ID和资源组名称
$subscriptionId = "your-subscription-id"
$resourceGroupName = "your-resource-group-name"
# 分配Reader角色
New-AzRoleAssignment -ServicePrincipalName $applicationId `
                     -RoleDefinitionName "Reader" `
                     -Scope "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"

修正后的完整脚本示例

# 提前定义变量
$applicationName = "Your-App-Display-Name"
$certFilePath = "C:\temp\your-cert.pfx"
$certPassword = "Your-Secure-Password"

# 创建自签名证书
$cert = New-SelfSignedCertificate -CertStoreLocation "cert:\CurrentUser\My" -Subject $applicationName -KeySpec KeyExchange -NotAfter (Get-Date).AddYears(1)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())

# 创建应用注册
$application = New-AzADApplication -DisplayName $applicationName 
$objectId = $application.Id
$applicationId = $application.AppId

Write-Host "ID: $($objectId)   -   AppID: $($applicationId)"

Start-Sleep -Seconds 2

# 创建服务主体并关联证书(已修正参数)
$sp = New-AzADServicePrincipal -AppId $applicationId -CertValue $keyValue -CertStartDate $cert.NotBefore -CertEndDate $cert.NotAfter
Start-Sleep 5

# 分配Microsoft Graph读取权限(需管理员手动同意后生效)
Add-AzADAppPermission -ObjectId $objectId -ApiId "00000003-0000-0000-c000-000000000000" -PermissionId "5f8c59db-677d-491f-a6b8-5f174b11ec1d"

# 导出证书到PFX文件
$cert | Export-PfxCertificate -FilePath $certFilePath -Password (ConvertTo-SecureString -String $certPassword -Force -AsPlainText)

Write-Host "Generated Thumbprint: $($cert.Thumbprint)"
Write-Host "Certificate Created and placed in: $($certFilePath)"

# 示例:关联目标资源组(替换为实际信息)
$subscriptionId = "your-subscription-id"
$resourceGroupName = "your-resource-group-name"
New-AzRoleAssignment -ServicePrincipalName $applicationId `
                     -RoleDefinitionName "Reader" `
                     -Scope "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"

内容的提问来源于stack exchange,提问作者Bigbear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:52:20