question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

PowerShell global variable not retrieved correctly

See original GitHub issue

Variables are defined at the beginning of the PowerShell script; without the “global” keyword Assuming these variables are in global scope.

$accessTokenTest = ""`
$accessToken = ""`

Here is a function to renew the SQL access token and persist it to a JSON file. In Get-SQLToken function, global variables were saved differently, with and without “global” keyword. This was the workaround for the issue: $Global:accessToken = $tokenResponse.access_token

function Get-SQLToken {
    WriteToLog -message "Token Start..."
    try {
        $resourceURI = "https://database.windows.net/"
        $tokenAuthURI = $env:MSI_ENDPOINT + "?resource=$resourceURI&api-version=2017-09-01"
        $tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret" = "$env:MSI_SECRET" } -Uri $tokenAuthURI
        WriteToLog -message "Create new SQLSetting file"
        $tokenResponse | ConvertTo-Json | Out-File SQLSettings.json
        $Global:accessToken = $tokenResponse.access_token
        $accessTokenTest = $tokenResponse.access_token
        if ($null -eq $accessTokenTest || [string]::IsNullOrEmpty($accessTokenTest)) {
            WriteToLog -message "[DBG] Failed to save access token value to a global variable. accessTokenTest is $($accessTokenTest)"
        }
        else {
            WriteToLog -message "[DBG] Successfully save access token value to a global variable accessTokenTest. accessTokenTest is $($accessTokenTest)"
        }
    }
    catch [System.Exception] {
        WriteToLog -message "Error occured $($_.Exception.Message)" -Exception $_
        $tokenResponse = ""    
    }
    WriteToLog -message "Token end"
}

We retrieve the value of the global variables later on.
However, the variable $accessTokenTest was not retrieved correctly

   $SQLSettings = Get-Content SQLSettings.json | ConvertFrom-Json
    if ([datetime]$SQLSettings.expires_on -gt ((Get-Date).AddHours(23))) { # DBG AddMinutes(30)
        $accessToken = $SQLSettings.access_token
        WriteToLog -message "Token from SQLSettings"
    }
    else {
        WriteToLog -message "Old Token need a new Token... create new SQLSettings"
        Get-SQLToken
        if ($null -eq $accessTokenTest || '' -eq $accessTokenTest || [string]::IsNullOrEmpty($accessTokenTest)) {
            WriteToLog -message "[DBG] Failed to retrieve token value from a global variable. accessTokenTest is $($accessTokenTest)"
        }
        else {
            WriteToLog -message "[DBG] Successfully retrieved token value from a global variable accessTokenTest. accessTokenTest is $($accessTokenTest)"
        }
        $accessToken = $Global:accessToken
    }

In order to work around the hurdle, we applied the work around which seems redundant.

Save the value to the global variable $accessToken with global keyword

$Global:accessToken = $tokenResponse.access_token

Retrieve the value of the global variable $accessToken with global keyword

$accessToken = $Global:accessToken

From the logs,
2022-08-06T23:42:54.398 [Information] INFORMATION: [DBG] Successfully save access token value to a global variable accessTokenTest. accessTokenTest is<<value is redacted>>
no value got retrieved, or no printable value got retrieved
2022-08-06T23:42:54.399 [Information] INFORMATION: [DBG] Successfully retrieved token value from a global variable accessTokenTest. accessTokenTest is<<end of line>>

We have been running this script without work around since August 2021 under PowerShell 7 kernel until the issue started surfacing in early March this year. We would like to learn:

  1. What has been changed in PowerShell 7 kernel in function app?
  2. Is it required to declare global variables with 'global' keyword?

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
yihchuangcommented, Oct 20, 2022

Hi @Francisco-Gamino,

Thank you for the reply, I will create a support ticket and provide the info as requested.

For those lines of code that you pointed out, were added just for providing the Support additional info. Not in the production code.

0reactions
Francisco-Gaminocommented, Oct 27, 2022

@yihchuang – Sounds good, thank you. I will follow up with you via the support ticket. Closing issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

PowerShell global variable not retrieved correctly #869
Variables are defined at the beginning of the PowerShell script; without the “global” keyword Assuming these variables are in global scope.
Read more >
Powershell Global Variable usage as parameter to argument
AS INTENDED. Of course, I had to run the script and watch it error first, then re-run the script with the global variable...
Read more >
Powershell: The variable '$_' cannot be retrieved because ...
I'm trying to catch and print an Exception Stack Trace in a powershell code running on Azure Devops in a Release Pipeline.
Read more >
Retrieving variable value from a powershell script
Problem is, when I run the script with task it does not save the variable $token as powershell session is created just for...
Read more >
Not able to get the global variable to work in PowerShell.
Start PowerShell like this: pwsh -noprofile . You probably end up in the Home ( ~ ) folder. · Change the directory. Set-Location...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found