API bearer token not working

I have searched the forum but have not found an answer for my problem. I have written code that works if I login to swagger and hardcode the bearer token it returns, but when I generate my own bearer token it says I am not authenticated and to sign in.

$Accession = Invoke-RestMethod @wrParam
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| {“message”:“You are not authenticated!”,“errorCode”:0,“result”:null,“targetUrl”:null,“success”:false,“error”:{“code”:0,“message”:“You are not authenticated!”,“details”:“You should be authenticated (sign
| in) in order to perform this operation.”,“validationErrors”:null},“unAuthorizedRequest”:true,“__abp”:true}
InvalidOperation:

Here is my code:
$Script:ClientID = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’
$file = “xxxx\AccessionCount.csv”
function Get-CurrentToken {
param($ClientID = $Script:ClientID,
$Token = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’)

$body = @{client_id = $ClientID
grant_type = ‘refresh_token’
refresh_token = $Token
} | ConvertTo-Json
$header = @{
‘X-UiPath-TenantName’ = ‘xxxxxxxxxxx’
‘Accept-Type’ = ‘application/json’
}
Invoke-RestMethod -Method POST -Uri ‘https://account.uipath.com/oauth/token’ -Headers $header -Body $body -ContentType “application/json”
}
function Get-AccessionCount {
[CmdletBinding()]
param (
$EndPoint = “odata/RobotLogs?%24filter=ProcessName%20eq%20’BLG-MGL-GetWork’&%24select=Message&%24orderby=TimeStamp%20desc&%24top=1&%24skip=3”,
$Token,
# $ClientId = $Script:ClientID,
$ClientId = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’,
$ClientSecret = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’,
$Scope = ‘OR.Monitoring’,
$BLGMGL = xxxxxxxxxxxxx
)

[uri]$baseUri = ‘UiPath
$wrParam = @{
Uri = [uri]::new($baseUri, $EndPoint)
Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get
ContentType = ‘application/json’
Body = @{
# client_id = $ClientID
client_id = $ClientId
client_secret = $ClientSecret
scope = $Scope
# grant_type = ‘refresh_token’
grant_type = ‘client_credentials’
}
Headers = @{
Authorization = (‘Bearer {0}’ -f $Token)
Accept = ‘application/json’
‘X-UiPath-OrganizationUnitId’ = $BLGMGL
}
}
$Accession = Invoke-RestMethod @wrParam
$AccesionMessage = $Accession.value.Message
$AccesionCount = $AccesionMessage.split(‘-’)
$RunDate = Get-Date -Format “MM/dd/yyyy”
[PSCustomObject]@{
Count = $AccesionCount[0].trim()
Date = $RunDate
} | Export-Csv -Path $file -Append -NoTypeInformation
}

Get-AccessionCount -Token (Get-CurrentToken).access_token

Get-AccessionCount -Token ‘xxxxxxxxxxxxxxxxxxxxxxxxxx’

@lvnry2000
we would recommend to checkout the new approaches: