Question About Scoping and Script Blocks

Hey guys, I have a script to connect to MS Graph and pull some info. Initially, everything worked great, then I tried adding a timer to automatically re-create the authentication token before the original expired. I know global scoping isn’t ideal, but it’s not working right anyways. I can run it in VSC and it works great, but once I go to the shell, $token doesn’t get modified. Is the standard shell starting a new “session” for the timer action script block (so there would effectively be 2 global token variables that are in different globes)? How would you suggest passing the token back to the script if that’s the case? Is there a way to do it without global variables? Theoretically, I could send it to a file, but then I’m reading the file every time I make a request since it could have been updated between commands.

$Global:TimeoutTimer = New-Object timers.timer $Global:token = "none" $TimerAction = { $Global:tokenRequest = Connect-MicrosoftGraphCustom <Hidden Parameters> $Global:token = $Global:tokenRequest.access_token $Global:TimeoutTimer.Interval = ($Global:tokenRequest.expires_in * 1000) - 100000 } $job = Register-ObjectEvent -InputObject $Global:TimeoutTimer -EventName Elapsed -Action $TimerAction Write-Host $Global:token -ForegroundColor Green $Global:TimeoutTimer.Enabled = $true 

Any help is appreciated, thanks guys!

submitted by /u/mosesteawesome
[link] [comments]

Leave a Reply