首页 > 解决方案 > 在 Powershell 上以编程方式进行身份验证时无法运行 Skype 命令

问题描述

我在构建 Powershell 脚本时遇到了一个奇怪的问题。我想以编程方式连接到 Microsoft Teams 并执行一些 Skype for business 在线命令。

当我只是在终端上做

Connect-MicrosoftTeam并得到提示并导入我的凭据,一切正常,但我需要以编程方式进行。

我使用以下权限进行了应用注册

API 注册权限

我正在针对 Azure AD 和 Graph 进行身份验证:

#Connect to Graph
$Body = @{    
Grant_Type    = "client_credentials"
Scope         = "https://graph.microsoft.com/.default"
client_Id     = $ApplicationID
Client_Secret = $AccessSecret
} 

$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenatDomainName/oauth2/v2.0/token" -Method POST -Body $Body
$token = $ConnectGraph.access_token
#Connect to AD
$uri = "https://login.microsoftonline.com/${tenant_id}/oauth2/token"
$body = @{grant_type='refresh_token';resource='https://graph.windows.net';client_id=$clientId;refresh_token=$refresh_token}
$result = Invoke-RestMethod -Method Post -Uri $uri -Body $body
$accessToken = $result.access_token

然后我跑

Connect-MicrosoftTeams -AadAccessToken $accessToken -MsAccessToken $token -AccountId $account

而且它不会抛出错误,可以正常工作。我会运行类似Get-Team的命令并正确返回信息。但是,当我尝试运行类似 Skype 的命令时

 Get-CsOnlineVoiceUser

我得到错误

Get-CsOnlineSession : Run Connect-MicrosoftTeams before running cmdlets.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:63 char:22
+     $remoteSession = & (Get-CsOnlineSessionCommand)
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-CsOnlineSession], UnauthorizedAccessException
    + FullyQualifiedErrorId : UnauthorizedAccessException,Microsoft.Teams.ConfigApi.Cmdlets.GetCsOnlineSession
 
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:10006 char:38
+ ...    -Session (Get-PSImplicitRemotingSession -CommandName 'Get-CsOnline ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

我错过了什么吗?我正在使用 2.3.1 团队模块。

谢谢!

标签: powershellazure-active-directoryazure-functionsmicrosoft-teamsskype-for-business

解决方案


这有点棘手,但可以实现。

我建议阅读此博客文章以获取确切说明和代码示例: https ://paulobrien.co.nz/2020/06/29/s4b-online-powershell-modern-auth/

应该让你开始。


推荐阅读