Function Get-HelpscoutToken { #Fetches a cached bearer token for Helpscout authentication 2.0, refreshing it if necessary #returns the token as plaintext for easy integration into invoke-restmethod [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$helpscout_token_path, [Parameter(Mandatory=$true)] [securestring]$app_id, [Parameter(Mandatory=$true)] [securestring]$app_secret, [Parameter(Mandatory=$false)] [switch]$Force ) $token_request = "https://api.helpscout.net/v2/oauth2/token?grant_type=client_credentials&client_id=$(Get-PlainText $app_id)&client_secret=$(Get-PlainText $app_secret)" if (!(Test-Path $helpscout_token_path)){ Write-Debug "Acquiring helpscout authorization token" $response1 = Invoke-RestMethod -Method Post -Uri $token_request -ContentType "application/json; charset=UTF-8" $token = ConvertTo-SecureString -String $($response1.access_token) -AsPlainText -Force $secureStringText = $token | ConvertFrom-SecureString #save the token to disk New-Item -Path $helpscout_token_path -ItemType "file" -Value $secureStringText -Force | Out-Null }else{ $token = Get-Content $helpscout_token_path | ConvertTo-SecureString $timestamp = Get-Item -Path $helpscout_token_path | Select-Object -ExpandProperty LastWriteTime #check to see if the timestamp on the file is more than 2 hours old if(((get-date) -gt ($timestamp.AddSeconds(7200))) -or $force){ #if it is then acquire a new token $response2 = Invoke-RestMethod -Method Post -Uri $token_request -ContentType "application/json; charset=UTF-8" $token = ConvertTo-SecureString -String $($response2.access_token) -AsPlainText -Force $secureStringText = $token | ConvertFrom-SecureString #update the token to disk Set-Content -Path $helpscout_token_path -Value $secureStringText -Force } } return (Get-PlainText -SecureString $token) }