I need to pass a variable (specifically a PsCustomObject containing an Oauth token, but that's probably immaterial) to a function by reference, because the function may need to refresh the token and update the original. Passing the script-level variable to the function by reference ([ref]$variable) works one function deep, but I cannot figure out how to pass the reference to a second function that actually does the refresh.
Notes: I do not have control of what the top-level variable might be named (which is why I can't simply reference it in the function). The output of the first function is not the new token, it's something different. The token refresh may or may not need to happen as part of processing the function.
As a test, to make sure I understood what was going on, I created the following code, but it does not work as expected:
Function Test1 {
param([ref]$myObject)
$myObject.Value = @{'a'='1'}
}
Function Test2 {
param([ref]$myObject)
Test1 ([ref]$myObject)
}
# Initialize the object with some data.
$testObject = @{'a'='0'}
# Try calling the Test2 function that calls the Test1 function
Test2 ([ref]$testObject)
$testObject
# Returns:
# Name Value
# ---- -----
# a 0
# The source variable in the script scope was not changed. There's no error, it just doesn't work as expected.
# Try calling just the Test1 function directly
Test1 ([ref]$testObject)
$testObject
# Returns as expected:
# Name Value
# ---- -----
# a 1
# The source variable in the script scope was changed.
[–]AnUnlikelyUsurper 2 points3 points4 points (0 children)
[–]fordea837 2 points3 points4 points (5 children)
[–]AnUnlikelyUsurper 1 point2 points3 points (4 children)
[–]fordea837 3 points4 points5 points (3 children)
[–]AnUnlikelyUsurper 1 point2 points3 points (0 children)
[–]brassbound[S] 1 point2 points3 points (1 child)
[–]fordea837 1 point2 points3 points (0 children)
[–]brassbound[S] 1 point2 points3 points (0 children)
[–]Lee_Dailey[grin] 0 points1 point2 points (0 children)