r/PowerShell • • 5d 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.

12 Upvotes

46 comments sorted by

5

u/dodexahedron 5d 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.

3

u/da_chicken 5d 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 4d ago

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

1

u/chrusic 2d ago

1

u/SymfonyWonderer2 3h ago

You're right, by definition, I don't know how to do 'X', but I think that 'Y' might help, which, I also don't know how to do. So shouldn't I ask about 'Y' and eventually 'X'?

Mostly everything about PowerShell is new or unknown to me, and of what I'm aware of, isn't deeply known even after my repeatedly going over what's 'out there' to read about PowerShell. How long do you think I should necessarily wait before asking questions on what I so far am not fully understanding?

1

u/SymfonyWonderer2 4d 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?

2

u/surfingoldelephant 4d ago edited 4d 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.

0

u/SymfonyWonderer2 4d ago

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

2

u/spikeyfreak 4d 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/ankokudaishogun 3d ago

So Copilot' answer is wrong again

Due a number of reason, LLM are really, REALLY bad at Powershell.
If you use them, take their answers as pseudo-code and never trust them being any kind of right.

1

u/SymfonyWonderer2 4d 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 4d ago edited 4d 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.

0

u/SymfonyWonderer2 4d ago

Nothing as long as all of the variables in all of script used in a program are unique.

I understand that the contents of the path Variable: is similar to a drive volumn, but I don't know how to view the 'directory' or the 'files' contents. Do they exist past the execution of the script that created them? What about the same named variable used in diferent scopes?

1

u/MonkeyNin 3d ago

I can't install a debugger or use one if it came preinstalled.

Oh if that's the reason, you don't need one. For example try this:

function DoSomething { 
    param( [int] $x )     

    if( $x -gt 5 ) { 
      wait-debugger
      return $x + 1
    } 

    # else 
    DoSomething ( $x + 1 )
    DoSomething ( $x + 6 )
}

It conditionally starts the debugger even in a regular terminal.

Type ? for controls. It has the call stack You can inspect variables from other scopes from within the function's scope

$x
# 20

$script:x
# 99

or the same:

get-variable -name 'x' -Scope 0  # 20
get-variable -name 'x' -Scope 1  # 99

1

u/SymfonyWonderer2 2d ago

Thanks. I ran into a suspicious problem where I started loosing access to .ps1 files while I was editing and executing them, but I don't know why. I'm still the file owner and the Properties app shows that I should still have full access to the file, but with the file, that PowerShell v7.7 says it can't access, still in an editor, I find that if I save that file again, I'm told that I don't have access to that file, the automatic backup of that file, or have access to any new file I try creating. The only way to save my work is to copy all the text in the still open file to Notepad, and save it to a new file from there. The newly created file from Notepad remains accessible to me.

However, not wanting to work in Notepad, I've started using VS Code again. When I opened it after a time, it immediately updated itself, told me that a cupel of the PowerShell plug-ins were obsolete, disabled them, and VS Code has not crashed in two days.

So, while in there, I took a look at the PowerShell IDE, and for something that MS abandoned, it looks pretty good, actually better than many pay-for debuggers that I used professionally for other languages. Makes me suspicious of why MS who's retiring CMD.exe for PowerShell, would seemingly dump their IDE. Any way, I'm using it and VS Code for the foreseeable future.

Thanks for the work around.

One question about VS Code, when it finds a spelling error, questionable code, or a coding error, it shows a clickable 'fix' option that does nothing. Seems not as if it's me directing VS Code to fix the issue, but rather, me telling VS Code that I'm going to fix it, or worse, me asking for permission to do so. Either way, it hasn't said, 'Oh, that's OK, I'll do that for you.' Is this an a subtle AI power grab?

1

u/spikeyfreak 4d 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/BlackV 4d ago

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

Also explained in the other posts you don't need to install a debugger, it's built I to PowerShell with set-psbreakpoint

1

u/SymfonyWonderer2 4d ago

Thanks for the code and clerification.

1

u/vermyx 5d 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 4d ago

Thanks!

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

1

u/SymfonyWonderer2 2d ago

I accidently found that command.

1

u/SymfonyWonderer2 3d ago

Is Get-PSCallStack the command you're talking about when you say:

"I would be looking at the stack"?

I tried Get-PSCallStack.InvocationInfo | write-host , but that didn't work.

Line |
235 | Get-PSCallStack.InvocationInfo
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The term 'Get-PSCallStack.InvocationInfo' is not recognized as a name of a
cmdlet, function, script file, or executable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.

The boundparameters property of InvocationInfo seems to have the function
call's arguments in a string, from which I can get the name of the variable who's
value is sent to my function with a named parameter.

1

u/coffeewap-vpc 3d ago

First of all, the reason that's not working is because "get-pscallstack.invocationinfo" essentially says "run a command/function named get-pscallstack.invocationinfo", which doesn't exist as we know.

What you need to do is a sort of "run this first, then treat the result as an object" approach. only then does ".invocationinfo" mean get this property.

That means, doing this instead:

(Get-PSCallStack).InvocationInfo

Also, piping the result into | Write-Host will simply output the typename instead (System.Management.Automation.InvocationInfo), since its .ToString() method doesn't return anything useful, so it falls back to just the type name.

It can be a bit confusing since it will work for alot of things, but alot of things not.. In this case it will not work (can also be tested by just calling '(Get-PSCallStack).InvocationInfo.ToString()' for example).

So if you do really want Write-Host, then the following will work:

(Get-PSCallStack).InvocationInfo | Out-String | Write-Host

Otherwise just omitting out-string and write-host will display the object's properties.

1

u/SymfonyWonderer2 2d ago

Thanks. However, I found that it isn't necessary to call

Get-PSCallStack because InvocationInfo and its properties are already in the local scope $MyInvocation, which I'm using:

  $MyFunctionName = $MyInvocation.MyCommand.name
  $MyStatement    = $MyInvocation.Statement

And, over at St*w, said "Why would you need that", "PowerShell isn't a programming language like C++", "You can't", or just ignored me. You know ignorance may be bliss, but it isn't a virtue, Take that St*w! Besides the people are very much nicer over here, not to take away from some exceptions that I found there. Oh, and St*w AI! Blocking access for a week, saying that I needed a break!

1

u/jborean93 4d 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 4d ago edited 4d 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.

2

u/jborean93 4d 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 4d 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 4d ago

The answer is Yes, all three.

1

u/BlackV 4d ago

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

1

u/SymfonyWonderer2 4d 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 4d ago edited 4d 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/BlackV 4d ago

Splatting ;)

1

u/SymfonyWonderer2 4d ago

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

1

u/BlackV 4d ago

It does not solve your problem at all, it's just a good habit

But I was just poking some fun at you based on your last posts

1

u/coffeewap-vpc 3d ago

What's the reason for using scopes in this way? Can you show us what your myfunc function does? is the value that myfunc is returning something that is computed within myfunc?

Can you explain a bit more what you are trying to solve here? Feels a bit ambigous, if you could explain a bit more detailed maybe we could be of more help

1

u/SymfonyWonderer2 14h ago

The problem has been solved. The goal was a 'somewhat' minimal drop-in debugging tool that I will use even though I'm now using VS Code and its IDE, fewer buttons to click now that its working. This effort was also valuable to me. I learned a lot and met many helpful people!

I was chasing this wrong way with the line of reasoning I was perusing by using the variable's name to get get the information for the variable name. However GV could find another variable with the same name, an index or temporary variable, that was closer scope-wise to the GV, or not at all, if myFunc was called from a part of the script that wasn't in myFunc's scope. Uniquely naming myFunc's local variables only fixed some of the incorrect finding issues, but it didn't fix the out of scope issue. To do that I needed to also send in the variable's value, which seemed redundant to me, and was a weak point in my method. So I began looking for a way to not send the name at all, and instead determine the name inside of myFunc.

Soon after, it was suggested that I give up on GV, and use the stack to get the information I wanted, This would allow me to only use the variable's value. I did this, and after more Googling, I found the Get-CallStack command and then these variables:

$MyInvocation.MyCommand.name and $MyInvocation.Statement that gave me the specific myFunc's call line text and its line number, another property, to get the variable's name and know that myFunc has the right call instance and variable. This was something I had asked about a month or so ago in St*w, in an unrelated question, to which I go back "Power wasn't C++", "Can't be done", "Why did I need that", but nothing about Get-CallStack. Anyway, I'm happier over here.

Don't believe their "press", the people here a friendlier and apparently smarter, too. ;P

1

u/KevMar Community Blogger 4d 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.

1

u/SymfonyWonderer2 4d ago

Yes, but the variable being myFunc function's scope is the core issue. myFunc is created in the script file's script scope level, so it can be called anywhere in the script, but only the variables with Global(1), Script, Local(0), AllScript, or an ancestor, will be in myFunc's scope for GV and GN to see them. To prevent myFunc's locally defined variables from hiding any variables created outside of myFunc, they should be uniquely named. That's fine, and all of my test cases show that GV and GM work with the script scoped defined or set variables. However, for variables created inside of child functions of myFunc or in an adjacent function, and are then out of myFunc's scope, thus preventing GV and GM (inside myFunc) from finding them.

Passing-in the variable's name via a parameter won't give the needed scope to these commands, and passing-in the variable's value, perhaps as a [ref] type might help, if GV and GM can 'see' past the [red] parameter to the actual variable. Once the [ref] to the variable is in myFunc, then it can be piped into GV and GM, but these commands work differently when a value is given this way to these commands. If the output of the commands is better for me when using the variable's name is given to these commands, then passing-in the variable's name to myFunc, cloning the [ref] parameter to a local value variable, 'feeding' this to GV and GM, and substituting the original variable's name into GV's output can solve this issue, as long as the copy|clone is deep enough, and data and types are not changed.

1

u/SymfonyWonderer2 13h ago

My idea was mostly right, but the actual solution is simpler. You don't need
to pass-in the variable's name or use GV, nor do you need to worry about
local variable names or scope. Lastly, you don't need to call Get-CallStack
or 'mess around' with the call stack. You just need to use a local auto-variable
and, this property: $MyInvocation.Statement.

This will give you the text of the line of the line making the call of the stack
frame that was pushed onto the stack. Then you can parse-out the variable's
name. If you use the variable to pass a value or reference into a function that
you wrote or have the function's signature, then you know what parameter is
getting your value, which makes the parsing of the name from the Statement
easier from where ever the call went.

3

u/surfingoldelephant 4d 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

2

u/purplemonkeymad 4d 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 4d ago

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