Teams虚拟用户在线维持脚本报错:哈希字面量缺少等号
问题排查:PowerShell脚本哈希字面量缺少“=”错误
问题场景
编写了一个PowerShell脚本用于维持Microsoft Teams中2个虚拟用户的在线状态,确保队列能正常呼叫转接,但运行时提示三处“哈希字面量缺少=”错误,已检查括号、逗号等语法但未发现问题。
错误原因
脚本中三个哈希表的最后一个键值对后存在多余的逗号,PowerShell解析时会认为后续还有键值对定义,但实际没有,因此触发“缺少=”的语法错误。此外还有一处潜在问题:$users数组为空,需要填入目标用户的标识。
解决方案
- 移除每个哈希表最后一个键值对末尾的多余逗号
- 补充
$users数组中的用户UPN或ID - 确保Azure AD应用已授予
Presence.ReadWrite.All应用权限(调用Graph API必需)
修正后的完整脚本
# Graph API Details $tenantId = "***" $clientId = "***" $clientSecret = "***" # Function to get OAuth token function Get-OAuthToken { param ( [string]$tenantId, [string]$clientId, [string]$clientSecret ) $body = @{ grant_type = "client_credentials" scope = "https://graph.microsoft.com/.default" client_id = $clientId client_secret = $clientSecret } $response = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -ContentType "application/x-www-form-urlencoded" -Body $body return $response.access_token } # Get the OAuth token $token = Get-OAuthToken -tenantId $tenantId -clientId $clientId -clientSecret $clientSecret # Users to keep online - 替换为实际用户UPN或ID $users = @("user1@yourdomain.com", "user2@yourdomain.com") # Function to set user presence status to available function Set-UserPresence { param ( [string]$user, [string]$token ) $uri = "https://graph.microsoft.com/v1.0/users/$user/presence/setPresence" $headers = @{ Authorization = "Bearer $token" Content-Type = "application/json" } $body = @{ sessionId = [guid]::NewGuid().ToString() availability = "Available" activity = "Available" expirationDuration = "PT1H" } $jsonBody = $body | ConvertTo-Json Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $jsonBody } # Loop to keep users online while ($true) { foreach ($user in $users) { Set-UserPresence -user $user -token $token Write-Output "Set presence to Available for $user at $(Get-Date)" } # Wait for 5 minutes before setting the presence again Start-Sleep -Seconds 300 }
额外说明
- 若仍出现语法错误,检查是否存在不可见的特殊字符(如全角符号),可将脚本复制到纯文本编辑器(如Notepad++)查看
- 调用Graph API的应用必须在Azure AD中完成权限配置并授予管理员同意,否则会返回权限不足的错误
内容的提问来源于stack exchange,提问作者Niklas
相关产品推荐
相关产品推荐

