Is it possible to have a function return the name of the variable that stores it?
i.e $a = myFunction
and have the function know that it is held in $a, when $a is dynamically assigned to it in a shell?
Is it possible to have a function return the name of the variable that stores it?
i.e $a = myFunction
and have the function know that it is held in $a, when $a is dynamically assigned to it in a shell?
function test() {
write-Host "Called by: $($MyInvocation.Line)"
}
$a = test
Which outputs
Called by: $a = test
?
I don't think this is possible at all, nor would it make much sense.
It's like expecting the integer 42
to know if it has been stored in the variable $answer
.
Once a function returns, only its return value (if any) is stored in a variable (if an assignment is actually used). If Get-Answer
returns 42
and you issue the command $answer = Get-Answer
, then $answer
will indeed contain 42
, but no record will be kept of the fact that it was stored there by having it returned from a function; for all intents and purposes, the end results of $answer = 42
and $answer = Get-Answer
are identical, if Get-Answer
does indeed return 42
.
Also, the assignement (if any) only happens after a function returns; the function only provides a return value (if it does); it doesn't and shouldn't care what PowerShell is going to do with this value after it returns; and its return value could very well be discarded instead of being assigned to anything. There is no direct link between $answer
and Get-Answer
: what PowerShell does when faced with a command like $answer = Get-Answer
is:
Get-Answer
Get-Answer
$answer
None of the players has any knowledge of this link; the function doesnt know what its return value will be used for, and the variable doesn't know where its assigned value comes from.
And even if some record was kept of this assignment having ever happened, it definitely wouldn't have happened yet while Get-Answer
was still being executed.
With the minimal info you've shared, this is the best guess I could make.
I'm going largely on your statement of "pass some other output into a different function"
myFunction1 {
...code...
return $someThing
}
myFunction2 {
param ($param1)
...code...
}
Usage
$a = myFunction1
myFunction2 $a
Be aware that echo's or write-hosts cmds within a function are ALSO return values. Use write-debug for debug info, or if you really need that info "returned" return is as an array (or a custom object)
return @($var1, $va2, $var3)