0

I need to run the below script with Task scheduler after every 15 min (to refresh the token before it expires). I have a another script which would use the 'Token value' by calling the function 'getToken'.

Problem is, when I run the script with task it does not save the variable $token as powershell session is created just for the task. When script being executed without the task, I can use 'getToken' value. Creating a global variable did not help/

Is there a solution to this or any other way around?

$refreshTokenBody = @{  grant_type = 'refresh_token'
                    client_id = 'clientID'
                    refresh_token= 'TokenNumber123124'}

$tokenRefresh = Invoke-RestMethod -Method Post -ContentType  "application/x-www-form-urlencoded" -Uri "https://url.com" -Body $refreshTokenBody 
$Global:token = $($tokenRefresh.access_token)

Function getToken{ 
       return $token
}
0

PowerShell only persists variables throughout the course of the script's execution. You should look at writing the variable out somehow for later reuse. Personally I like the registry for this but the file system is also a valid choice.

$Config = Get-ItemProperty "HKLM:\Software\yourregkey"
# Write to registry with this.
New-ItemProperty $Config -Name <Variable Name Here>  -Value <value here> -Type string -Force
# Read from registry with this. 
$ReadFromReg =  $Config.<Variable Name Here>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.