Azure自动化Runbook获取应用注册所有者报错及需求解决
解决方案
一、修复“The term 'if' is not recognized”错误
这个错误本质是PowerShell语法格式问题,常见排查及修复点:
- 检查
if前的代码是否完整闭合:比如前一行命令是否遗漏括号、管道符|后未正确换行,导致PowerShell把if识别为前命令的参数而非关键字。 - 确认符号为半角:
if后的括号()、代码块的{}必须是英文半角,避免混入全角符号。 - 规范代码格式:
if关键字后必须跟空格,条件表达式后需换行或空格再接{,正确示例:if ($credential.EndDate -lt (Get-Date)) { # 执行逻辑 } - 检查脚本编码:若脚本在中文编辑器编写,可能存在隐藏非ASCII字符,可复制到Notepad++切换为UTF-8无BOM编码后重新保存。
二、获取Azure Entra ID应用注册所有者信息
前置准备
- 导入对应模块:在Azure自动化账户的「模块」中,导入
Microsoft Graph模块(推荐,AzureAD模块已逐步淘汰)或AzureAD模块。 - 配置权限:确保Runbook使用的服务主体拥有以下权限(需管理员同意):
- Microsoft Graph:
Application.Read.All、Directory.Read.All - AzureAD:
Application.Read.All、Directory.Read.All
- Microsoft Graph:
代码实现示例
使用Microsoft Graph模块(推荐)
# 获取所有应用注册 $apps = Get-MgApplication -All foreach ($app in $apps) { # 获取应用所有者 $owners = Get-MgApplicationOwner -ApplicationId $app.Id -All $ownerDetails = $owners | ForEach-Object { if ($_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.user') { [PSCustomObject]@{ Name = $_.DisplayName Email = $_.Mail } } elseif ($_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.servicePrincipal') { [PSCustomObject]@{ Name = $_.DisplayName Email = "服务主体: $($_.AppId)" } } } # 将所有者信息格式化为HTML友好的字符串 $ownerList = if ($ownerDetails) { $ownerDetails | ForEach-Object { "$($_.Name) <$($_.Email)>" } -join "<br>" } else { "无所有者" } # 处理凭据过期天数逻辑 $credentials = Get-MgApplicationPassword -ApplicationId $app.Id foreach ($cred in $credentials) { $expiryDays = ($cred.EndDateTime - (Get-Date)).Days # 构建最终输出对象 [PSCustomObject]@{ 应用名称 = $app.DisplayName 凭据名称 = $cred.DisplayName 剩余过期天数 = $expiryDays 所有者信息 = $ownerList } } }
使用AzureAD模块
# 服务主体身份验证(Runbook中需配置对应参数) Connect-AzureAD -TenantId $tenantId -ApplicationId $appId -CertificateThumbprint $certThumbprint # 获取所有应用注册 $apps = Get-AzureADApplication -All $true foreach ($app in $apps) { # 获取应用所有者 $owners = Get-AzureADApplicationOwner -ObjectId $app.ObjectId $ownerList = if ($owners) { $owners | ForEach-Object { if ($_.ObjectType -eq 'User') { "$($_.DisplayName) <$($_.UserPrincipalName)>" } elseif ($_.ObjectType -eq 'ServicePrincipal') { "$($_.DisplayName) (服务主体: $($_.AppId))" } } -join "<br>" } else { "无所有者" } # 处理凭据过期天数逻辑 $credentials = Get-AzureADApplicationPasswordCredential -ObjectId $app.ObjectId foreach ($cred in $credentials) { $expiryDays = ($cred.EndDate - (Get-Date)).Days [PSCustomObject]@{ 应用名称 = $app.DisplayName 凭据名称 = $cred.DisplayName 剩余过期天数 = $expiryDays 所有者信息 = $ownerList } } }
常见问题排查
- 若无法获取所有者,先确认服务主体的权限已完成管理员同意,权限范围是否正确。
- 部分应用可能无所有者,需在代码中处理空值情况,避免输出异常。
内容的提问来源于stack exchange,提问作者Jude Clermont
相关产品推荐
相关产品推荐

