我正在连接到Microsoft Graph以获取一些报告。但是,如果报告接近一个小时,我希望自动重新请求令牌。我可以让脚本在Visual Studio Code中工作,但它不会更新普通shell中的token或TimeoutTimer变量。我希望能够将其作为计划任务运行,因为运行时间约为8小时。
我假设这是由于作用域的原因,但我希望Global能工作,但事实并非如此。我也尝试过使用$job.Module.SessionState.PSVariable.Set()来设置一个“状态”变量,但是没能让它工作起来(不是很熟悉,所以只是结束了我所看到的其他一些东西)。
$Global:TimeoutTimer = New-Object timers.timer
$Global:token = "none"
$TimerAction = {
$Global:tokenRequest = Connect-MicrosoftGraphCustom "Secret Parameters"
$Global:token = $Global:tokenRequest.access_token
$Global:TimeoutTimer.Interval = ($Global:tokenRequest.expires_in * 1000) - 100000
Write-Host "Inside action: $($Global:TimeoutTimer.Interval)" -ForegroundColor Green
}
$job = Register-ObjectEvent -InputObject $Global:TimeoutTimer -EventName Elapsed -Action $TimerAction
$Global:TimeoutTimer.Enabled = $true
sleep -Milliseconds 100
$i = 0
while ($i -le 5)
{
Write-host "Function Return: $($token)" -ForegroundColor Red
Write-Host "Global Variable: $($Global:Token)" -ForegroundColor Gray
Write-Host "Timer Expires in: $($TimeoutTimer.interval) or $($Global:TimeoutTimer.interval)" -ForegroundColor Blue
sleep 3600
$i++
}
$Global:timeoutTimer.Enabled = $false
我希望得到一些"Inside action: x“输出,然后在循环过程中得到一些令牌的副本。我在shell中得到的只是一堆"None“和"Timer expires in 100 or 100”
如何才能让token的值在适当的作用域中更新,而不是每次访问token变量时都读取文件?
发布于 2019-05-21 03:15:53
下面是一个如何更改变量的示例,即使是非全局变量。这个想法是通过使用GetNewClosure
创建闭包,并将token放入另一个对象(在我的例子中是哈希表):
$timer = New-Object System.Timers.Timer(1000)
$tokenObj = @{}
$sb = {
$random = New-Object System.Random
$tokenObj['token'] = $random.Next(100)
}.GetNewClosure()
Register-ObjectEvent -InputObject $timer -EventName 'Elapsed' -Action $sb
$timer.Start()
for ($i = 0; $i -lt 20; $i++)
{
Write-Host "Token value: $($tokenObj['token'])"
Start-Sleep -Milliseconds 400
}
https://stackoverflow.com/questions/56226019
复制相似问题