简体   繁体   中英

How to define a global variable in Powershell

I am trying to define a variable globally in powershell and get the value in one function and pass that value in different function but I am unable to do so. I googled and tried $global:myvariable but its not working. what wrong am i doing?

here is my code:

$global:namerel = $null
Function GET-value{
$uriAccount = $orz + "_apis/release/releases/1914?api-version=6.0"
$responseRels = Invoke-RestMethod -Uri $uriAccount -Method get -Headers $AzureDevOpsAuthenicationHeader 
$namerel = $responseRels.Name
write-host $namerel # it prints the required value
}

Function GET-rel{
$test = GET-value
write-host $namerel # nothing gets printed. its blank
}

To use a variable scoped global , you need to use syntax $global:namerel inside the functions. Without that, variable $namerel will be just a new variable, local to that function.

Also, you may not need to use global . Scope script usually is broad enough. See About_scopes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM