如何用PowerShell将Azure凭据存储到Microsoft Graph并复用连接命令?
使用PowerShell存储凭据以复用Microsoft Graph连接命令
一、存储交互式用户账户凭据(手动操作场景)
适合日常手动执行脚本的场景,将你的Azure AD用户凭据加密存储到本地,后续直接调用即可跳过手动输入步骤。
- 先确保已安装Microsoft Graph PowerShell模块(未安装则执行):
Install-Module Microsoft.Graph -Force -AllowClobber
- 加密存储凭据到本地文件:
# 弹出凭据输入窗口,输入你的Azure AD账户密码后,将凭据加密保存到指定路径 Get-Credential | Export-Clixml -Path "C:\MyScripts\GraphUserCreds.xml"
提示:
Export-Clixml会用当前Windows用户的凭据加密文件,仅当前账户能解密,请勿共享该文件。
- 复用凭据快速连接Microsoft Graph:
# 导入存储的凭据 $userCreds = Import-Clixml -Path "C:\MyScripts\GraphUserCreds.xml" # 带权限范围连接(替换为你实际需要的权限) Connect-MgGraph -Credential $userCreds -Scopes "User.Read.All","Group.ReadWrite.All"
二、使用服务主体存储凭据(自动化场景)
如果是无人值守的自动化脚本,推荐用服务主体身份验证,避免依赖个人用户账户。
- 创建并配置服务主体(首次执行):
# 创建Azure AD应用注册和对应的服务主体 $app = New-MgApplication -DisplayName "GraphAutomationSP" -SignInAudience AzureADMyOrg New-MgServicePrincipal -AppId $app.AppId # 为服务主体分配所需的Microsoft Graph权限(示例:读取所有用户) $graphSP = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'" $targetPermission = $graphSP.AppRoles | Where-Object {$_.Value -eq "User.Read.All"} New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId (Get-MgServicePrincipal -Filter "AppId eq '$($app.AppId)'").Id ` -PrincipalId (Get-MgServicePrincipal -Filter "AppId eq '$($app.AppId)'").Id ` -ResourceId $graphSP.Id ` -AppRoleId $targetPermission.Id
- 生成并存储服务主体的客户端密码:
# 创建服务主体的客户端密码 $clientSecret = New-MgApplicationPassword -ApplicationId $app.AppId -PasswordCredential @{DisplayName = "AutomationSecret"} # 封装服务主体凭据并加密存储 $spCreds = [PSCredential]::new($app.AppId, (ConvertTo-SecureString $clientSecret.SecretText -AsPlainText -Force)) $spCreds | Export-Clixml -Path "C:\MyScripts\GraphSPCreds.xml" # 存储租户ID(后续连接需要) $tenantId = (Get-MgContext).TenantId Set-Content -Path "C:\MyScripts\GraphTenantId.txt" -Value $tenantId
- 复用服务主体凭据连接Microsoft Graph:
# 导入存储的服务主体凭据和租户ID $spCreds = Import-Clixml -Path "C:\MyScripts\GraphSPCreds.xml" $tenantId = Get-Content -Path "C:\MyScripts\GraphTenantId.txt" # 使用服务主体身份验证连接 Connect-MgGraph -ClientId $spCreds.UserName -TenantId $tenantId -ClientSecret $spCreds.Password
注意事项
- 加密的凭据文件仅能在创建它的用户账户和机器上解密,跨机器/账户无法使用。
- 服务主体的客户端密码有过期时间,需定期轮换更新。
- 务必根据实际业务需求调整
-Scopes参数,避免申请超出必要的权限。 - 禁止将凭据文件、客户端密码提交到版本控制系统(如Git),防止泄露。
内容的提问来源于stack exchange,提问作者John mathews
相关产品推荐
相关产品推荐

