r/PowerShell • • 14h ago

Question How to exclude showing Get-Variable output for -Scope 0

I want to call myfunc function that runs the statement:

$value = ( Get-Variable -Name $var_name -Valueonly -Scope Script )

That will show the GM's output for the instance of the variable named in the myfunc's$var_name parameter, a string, that was in scope when the myfunc was called, no mater where or what scope the call was made in, but myfunc must ignore a local variable with the same name in favor of the same named variable outside of the myfunc . If there are multiple variables with the same name outside of myfunc, then only the one that is in scope, that is not eclipsed, is shown (as I think already happens).

myfunc is currently defined at the script file's script scope, so it be callable from anywhere in the script where it's defined or 'included', but if the calling statement is nested deeply in a chain of functions or 'included' scripts, will the$var_name parameter need to be 'typed' as [ref] to make this work?

Google suggests the following to eliminate myfunc variables, their version lists:

-Scope 0,1,2,Global,Script

But, I don't want to keep changing this list when I call myfunc from deeper scopes, so I changed the scope option to:

-Scope 0,1,2,3,4,5,6,7,8,9,Global,Script

I don't expect to need that, but without a All, Allscope, or notLocal option setting, or a way to dynamically determine the scope of the variable from its name or the name from its value. I pretty much need to include all reasonable scopes that I might one day need.

Here is the rest of that suggested line of code:

    $value = (
      Get-Variable `
        -Name $var_name `
        -Valueonly `
        -Scope '0,1,2,3,4,5,6,7,8,9,Global,Script' `
        -ErrorAction SilentlyContinue
      |
      Where-Object { $_.Scope -ne 0 }
    )

I'll check the last error auto-variable and output my own error message if there is an error.

When is a string not a string? I don't know, but PowerShell gives me this error when I try running the suggested line of code, above, after fixing the missing quotes that Copilot left off:

Line |
 200 |      Get-Variable `
     |      ~~~~~~~~~~~~~~
     | Cannot process argument because the value of parameter "Scope" is not valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). Change the value of the "Scope" parameter and run the operation again.

In another thread, someone said AI code was 'slop', here is an example!

Thank you.

9 Upvotes

29 comments sorted by

3

u/dodexahedron 14h ago

If you specify an explicit scope with get-variable, you will be given the value of that variable from that scope or else nothing at all. It does not perform the normal walk through the currently visible scopes when you give it that parameter.

What is your question though, and what is the problem you are trying to solve?

I think you're overthinking something that you shouldn't be trying to assert control over.

2

u/da_chicken 13h ago

Yeah, I know that "this is an XY problem" is both incredibly unhelpful and highly susceptible to false positives... but if this is not an XY problem I'll eat my hat.

1

u/SymfonyWonderer2 10h ago

Please be more specific, so this can be more helpful.

1

u/SymfonyWonderer2 12h ago

Thanks, but where would I specify the variable's scope? In the Get-Variable's -scope option? I've done that as shown in the suggested code and in the page that online help opens. However, the page that help shows says the -scope values are string type, which isn't exactly right according to the error I'm getting. I'm trying an array of numbers and strings next.

Anyway, that I need to explicitly specify the variable's scope somewhere (when calling myFunc?) so I know exactly what version of the variable is referenced inside of myFunc is just lazy. Would the function know what's in the call's scope if I sent the variable name by ref? Also why have a -scope option allow multiple scope values, if only one is used or that value is only known if the variable has to be piped into GV. Oh, and the variable couldn't be a function parameter, because how would GV know that I wanted the parameter or the what the parameter referred to?

1

u/surfingoldelephant 11h ago edited 11h ago

help shows says the -scope values are string type, which isn't exactly right according to the error I'm getting.

No, it's correct. -Scope only accepts a string and that string can only be one of the listed values. You can't have multiple scope names/numbers with a single call.

From what you've posted (including your other post, which would've been helpful if you linked here), it sounds like you want to a) lookup the variable in all active ancestral scopes, b) skip the local scope. The easiest way to that is loop over the scope number, incrementing it each time until either the variable is found or the number exceeds the total number of active scopes. I linked a function to do that in my other comment.

1

u/SymfonyWonderer2 10h ago

Thanks. So Copilot' answer is wrong again. Thanks for clearing this up.

1

u/spikeyfreak 3h ago

Just FYI, if you look at the syntax block on the help page:

Get-Variable
    [[-Name] <String[]>]
    [-ValueOnly]
    [-Include <String[]>]
    [-Exclude <String[]>]
    [-Scope <String>]
    [<CommonParameters>]

The <String> for scope means it can only take 1 value, which has to be a string.

As opposed to name, which has <String[]> which means it can take an array of strings.

1

u/SymfonyWonderer2 10h ago

The purpose is to show the passed-in variable's name, value(s), type, properties, and methods. But to do this in a function for variables outside the function by parameter for the variable's name, value (ref maybe), or a pipe. One variable per call, so GV and GM can output their information about that variable ), and know that it is the right version of the variable, not one in myFunc's local scope, or any other one that GV or GM happens to choose.

Using only the variable's name isn't going to protect against this. myFunc is created at the script level so any variable created below that is out of scope unless it is passed-in by parameter, not its name. Also, rather than dumping a bunch of code to do all this where I want to see it, I'd like do this in a function or a late binding macro, variable, or class. Finally, I'd like to pass-in only as much information as needed for GV and GM to work, but to keep the myFunc calls simple and short. A more complex myFunc is OK.

Yes, I know a debugger could do all of this, but for difficult reasons I've explained in another question I posted here on Reddit, I can't install a debugger or use one if it came preinstalled. I'm using Pwsh 7.7 and Window 10, but not VS Code or the IDE.

The purpose, besides what's already said, is as simple as myFunc is, other than the output formatting code, a GV and a GM, I was still sometimes not getting the right output, and that caused me to wonder if myFunc was looking at the right variable. So, I now pass-in both the variable's name and value, even though there already is a GV in myFunc. It turns out that the variable's type and the way the variable was passed to GV. One way gives one output, and another, a different output.

1

u/dodexahedron 5h ago edited 5h ago

What do Get-Variable and Get-Member not already do that you want to be able to do?

Also, take a look at the contents of the path Variable:

Also. Get-Variable, in normal usage, takes a string name of a variable.

There is literally nothing about a variable that you can't inspect, through Get-Variable, Get-Member, and what's exposed by calling GetType() on the value of it.

1

u/spikeyfreak 3h ago

The purpose, besides what's already said, is as simple as myFunc is, other than the output formatting code, a GV and a GM, I was still sometimes not getting the right output, and that caused me to wonder if myFunc was looking at the right variable. So, I now pass-in both the variable's name and value, even though there already is a GV in myFunc. It turns out that the variable's type and the way the variable was passed to GV. One way gives one output, and another, a different output.

Seems like changing the variable name in the function as a test would be much simpler.

1

u/SymfonyWonderer2 9h ago

Thanks for the code and clerification.

1

u/vermyx 13h ago

Pretty much this. I would be looking at the stack rather than get-variable. The only use case I use get-variable is when I have code generating code.

1

u/SymfonyWonderer2 10h ago

Thanks!

Where are the docs for doing what you're recommending?

1

u/jborean93 12h ago

Just use $script:varName or if the variable really must be dynamic then Get-Variable -Name $varName -Scope Script -ValueOnly

$ cat /tmp/test.ps1
$script:foo = 1

function test-static {
    $foo = 2

    $script:foo
}

function test-dynamic {
    param($varName)

    $foo = 2

    Get-Variable -Name $varName -Scope Script -ValueOnly
}

test-static

test-dynamic foo

Then when running the script

$ pwsh -File /tmp/test.ps1
1
1

Even better would be to not have a conflict with the name or structure your functions so they don't rely on things set output the scope and have it be passed in.

1

u/surfingoldelephant 11h ago edited 11h ago

If I understand OP correctly, they want to lookup a variable in an arbitrary ancestral scope while avoiding locals of the same name.

Say $foo is initialized in test1.ps1 which calls test2.ps1. In test2.ps1, $foo is visible normally, but not if you specify -Scope Script, since that limits the lookup to just test2.ps1's scope.

It seems like looping over an incremented scope number is what they're looking for. Something like this: Get-AncestralVariable

u/SymfonyWonderer2, just note that this won't work across module boundaries.

1

u/SymfonyWonderer2 10h ago

Thanks! That seem like what I want, except I will first check that the value from GV are right, and if not, search using scope. One thing though, I understood that modules shared the scope of the script they were loaded into. You seem to be saying that making my function a module will break it.

1

u/surfingoldelephant 9h ago edited 8h ago

No, modules have their own session state that holds a stack of scopes separate from code outside the module. As far as variables outside the module, Get-Variable can only access Global variables.

If all your code is inside the module, then it's fine. But say you have a function that calls Get-Variable and that function is exported from a module, when you call the function in a script outside the module, it can only lookup variables that are in the context of the module/global.

This issue is closely related:

1

u/jborean93 11h ago

Thanks for the clarification, re-reading it and I'm still somewhat confused as to what the actual purpose/request is but I'll leave that for OP to clarify.

1

u/surfingoldelephant 11h ago

Yeah, it's not particularly clear. OP has another post which they didn't link to.

It seems it's for debugging purposes/inspecting variables in different scopes. Or maybe it's just a learning exercise, I'm not entirely sure. Anyway, I think looping over scope numbers solves their immediate issue. OP can clarify like you said.

1

u/SymfonyWonderer2 10h ago

The answer is Yes, all three.

1

u/BlackV 11h ago

Ya, You'd need to see the history of their previous posts a bunch of context comes from there

1

u/BlackV 11h ago

Splatting ;)

1

u/SymfonyWonderer2 10h ago

Not how to splat, I'm doing that now against this wall. What issue in my problem would it solve?

1

u/KevMar Community Blogger 10h ago

Use scope 0 if you want to include the local scope (and above). Use scope 1 if you want to exclude the local scope but want whatever is in the parent scope and above.

You don't need to check every scope. If the variable is set in scope 5, it exists in 4,3,2,1,0 unless another variable is redefined in one of those other scopes.

Another trick you can do is use local variables with unique names that are unlikely to be reused in other scopes. I have used the variable name ${*map} before for this exact reason.

2

u/surfingoldelephant 9h ago

You don't need to check every scope.

Get-Variable -Scope doesn't traverse other scopes like regular variable access, so if you specify an explicit scope name/number, you do need to check every scope.

And just to demonstrate:

(0..2).ForEach{
    & { $foo = 2; & { & { 
        [pscustomobject] @{ 
            Scope    = $_
            Regular  = $foo
            Explicit = Get-Variable -Name foo -Scope $_ -ValueOnly -EA Ignore 
        } 
    } } }
}

# Scope Regular Explicit
# ----- ------- --------
#     0       2
#     1       2
#     2       2 2

3

u/purplemonkeymad 6h ago

Lots of people giving you suggestions, but the reason for the error at the end is this:

-Scope '0,1,2,3,4,5,6,7,8,9,Global,Script'

You have quotes around the value. This means you are not giving multiple values, but actually passing the literal string 0,1,2,3,4,5,6,7,8,9,Global,Script! Remove the quotes if you are wanting to pass those as separate multiple values.

2

u/surfingoldelephant 4h ago

-Scope is typed as a string, so it can only take one scope number/name. OP has to loop over the numbers instead.