使用PowerShell+MS Graph发送Teams消息时如何声明user@odata.bind
解决New-MgChat报错'user@odata.bind'字段缺失的问题
问题根源分析
你的代码存在两个关键问题:
- 一对一聊天(
oneOnOne类型)要求成员数组包含两个不同的用户,但你当前使用了相同的用户ID,导致参数逻辑无效,触发了误导性的错误提示。 - PowerShell哈希表在序列化带有特殊字符的键(如
user@odata.bind)时,可能出现解析异常,导致Graph API无法识别该字段。
修正后的代码
方案1:使用JSON字符串定义请求体(推荐)
直接通过JSON字符串定义参数,避免哈希表序列化的问题:
Import-Module Microsoft.Graph.Teams # 连接Graph,确保权限包含Chat.ReadWrite Connect-MgGraph -NoWelcome -Scopes "Chat.ReadWrite", "User.Read" # 用JSON字符串定义参数,替换为两个不同的用户ID $paramsJson = @" { "chatType": "oneOnOne", "members": [ { "@odata.type": "#microsoft.graph.aadUserConversationMember", "roles": ["owner"], "user@odata.bind": "https://graph.microsoft.com/v1.0/users('当前用户ID')" }, { "@odata.type": "#microsoft.graph.aadUserConversationMember", "roles": ["owner"], "user@odata.bind": "https://graph.microsoft.com/v1.0/users('目标用户ID')" } ] } "@ # 转换为PSObject传递给BodyParameter $params = $paramsJson | ConvertFrom-Json $myChatSession = New-MgChat -BodyParameter $params # 发送测试消息 $messageBody = @{ ContentType = 'Text' Content = 'Test Chat Message' } New-MgChatMessage -ChatId $myChatSession.id -Body $messageBody
方案2:修正哈希表的键处理
如果坚持使用哈希表,确保特殊键的写法正确,且成员ID不同:
Import-Module Microsoft.Graph.Teams Connect-MgGraph -NoWelcome -Scopes "Chat.ReadWrite", "User.Read" $params = @{ chatType = "oneOnOne" members = @( @{ "@odata.type" = "#microsoft.graph.aadUserConversationMember" roles = @("owner") "user@odata.bind" = "https://graph.microsoft.com/v1.0/users('当前用户ID')" }, @{ "@odata.type" = "#microsoft.graph.aadUserConversationMember" roles = @("owner") "user@odata.bind" = "https://graph.microsoft.com/v1.0/users('目标用户ID')" } ) } # 可选:序列化验证,确认字段是否正常存在 # $params | ConvertTo-Json -Depth 3 $myChatSession = New-MgChat -BodyParameter $params $messageBody = @{ ContentType = 'Text' Content = 'Test Chat Message' } New-MgChatMessage -ChatId $myChatSession.id -Body $messageBody
额外注意事项
- 确保两个用户ID属于不同的Azure AD用户,一对一聊天必须包含两个参与方。
- 验证权限:委托权限使用
Chat.ReadWrite即可,应用权限需要Chat.Create。 - 可通过
ConvertTo-Json命令查看序列化后的JSON,确认user@odata.bind字段是否正常输出。
内容的提问来源于stack exchange,提问作者Ruben_PH
相关产品推荐
相关产品推荐

