![](/img/trans.png)
[英]The remote server returned an error : (401) Unauthorized - PowerShell - Microsoft Graph API
[英]Getting 401 Unauthorized Error - MS Graph/PowerShell
试图在 PowerShell 中掌握 MS Graph 的窍门。 在Azure中设置了应用注册,可以正常连接Graph了。
但是,一旦我尝试查询 Graph API,就会收到 401 未经授权的错误。 对于以下示例,我已将所有可能的设备/设备管理权限添加到 Azure 应用程序 API 权限。 请参见下面的代码:
[CmdletBinding()]
param (
[Parameter()]
[String]$Device
)
#Check if the module is installed
$GraphInstalled = Get-Module -ListAvailable -Name "Microsoft.Graph"
If (!$GraphInstalled) {
Write-Host "Microsoft Graph module not found." -f Yellow
Write-Host "Installing Microsoft Graph module. . ." -f Yellow
Install-Module -Name "Microsoft.Graph" -Repository "PSGallery" -Force -AllowClobber
}
Write-Host "Connecting to MS Graph. . ." -f Yellow
$AppID = 'x'
$TenantID = 'x'
$Certificate = 'x'
Connect-MgGraph -ClientID $AppID -TenantID $TenantID -CertificateThumbprint $Certificate
function Get-AzureADDevice {
[CmdletBinding()]
param(
[Parameter()]
[String]$Name
)
$GraphVersion = "v1.0"
$Header = @{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
try {
$Resource = "Devices/?`$filter=devicename eq '$Device'"
$Uri = "https://graph.microsoft.com/$GraphVersion/$($Resource)"
(Invoke-RestMethod -Uri $Uri -Headers $Header -Method Get).Value
}
catch{
Write-Host "An error occurred:"
Write-Host "$_"
}
}
Get-AzureADDevice -Name $Device
我们已经在我们的环境中进行了测试并得到了相同的 401-unauthorized 问题,我们发现我们不需要为它添加任何外部 function ,而不是我们可以使用Get-MgDevice
下面我们使用的脚本:
[CmdletBinding()]
param (
[Parameter()]
[String]$Device
)
#Check if the module is installed
$GraphInstalled = Get-Module -ListAvailable -Name "Microsoft.Graph"
If (!$GraphInstalled) {
Write-Host "Microsoft Graph module not found." -f Yellow
Write-Host "Installing Microsoft Graph module. . ." -f Yellow
Install-Module -Name "Microsoft.Graph" -Repository "PSGallery" -Force -AllowClobber
}
Write-Host "Connecting to MS Graph. . ." -f Yellow
$AppID = 'xxxxxxxxxxx'
$TenantID = 'xxxxxxxxx'
$Certificate = 'xxxxxxxxx'
Connect-MgGraph -ClientID $AppID -TenantID $TenantID -CertificateThumbprint $Certificate
Get-MgDevice -Filter "displayName eq '$Device'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.