通过非交互式 powershell 脚本连接到 Microsoft Teams

Connecting to Microsoft Teams through non-interactive powershell script

我正在尝试在 PowerShell 中编写一个 azure 函数来连接到 Microsoft Teams 帐户:

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "Running teams account setup."

[string]$userName = 'xxx'
[string]$userPassword = 'xxx'
[securestring]$secStringPassword = ConvertTo-SecureString $userPassword -AsPlainText -Force
Write-Host ($secStringPassword | Format-Table | Out-String)
[pscredential]$credentials = New-Object System.Management.Automation.PSCredential ($userName, $secStringPassword)
Write-Host ($credentials | Format-Table | Out-String)
Connect-MicrosoftTeams -Credential $credentials

我收到的错误消息基本上是: ERROR: password_required_for_managed_user: Password is required for managed user

我读到可能有必要将 -Credentials 替换为 -Identity,但我找不到任何关于如何实现它的文档。

为了解决这个问题,我们有第三种选择,将加密的凭据存储到计算机上的文件中。 PowerShell 脚本使用文件中的加密密码来创建凭据对象。 请通过以下链接。 link1 Link2

刚刚注意到您正在使用 Azure 函数,我不太确定这里的根本原因,但我在我这边做了一些测试,下面代码的 PowerShell 函数非常适合我:

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

$username = "<user Name>"
$passwd = "<PassWord>"

$secpasswd = ConvertTo-SecureString -String $passwd -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $secpasswd)
Connect-MicrosoftTeams -Credential $cred

#try to get a team name to test if connect to teams successfully
$team = get-team -groupID '0d06e74e-08e0-4ef6-9bb5-3113ca735407'
$body = $team.DisplayName


# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body
})

requirements.psd1的内容:

@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    'Az' = '5.*'
    'MicrosoftTeams' = '1.1.9-preview'
}

测试结果:

Azure 函数利用 Powershell 内核。

Powershell 核心似乎存在一个已知问题,该问题已报告给产品组并且已经解决。

参考: https://github.com/MicrosoftDocs/office-docs-powershell/issues/5950

进一步阅读,我没有看到关于此的预计到达时间。一旦有修复,预计将更新线程。

回到-identity,它只是一个开关参数(你不需要传递任何东西),它在当前环境中使用托管服务身份登录。我怀疑这可能适用于您的情况。如果您想尝试,下面是实现。

Connect-MicrosoftTeams -Identity