2

I have a need to access common properties within my class functions and, unfortunately, outside my class in other functions.

For example

Class Myclass { [Void]my_function(){ $file_location = "$myvar" } } properties { # some props $myvar = "somefile.txt" } function do_things{ echo $myvar } 

When I attempt to access $myvar within my_function as part of the class, I get a parsing error "variable is not defined in the method" which makes sense as the variable isn't declared in the class, but I would imagine things in a properties block would be usable.

I'm hoping there is something I"m not aware of and haven't been able to find in the documentation that allows me to do this. It seems rather silly that I can't use properties within my class functions.

My current (unfavorable) solution is to have my class inherit from another class that just has a bunch of static variables defined in it since you can access those anywhere else in the script by doing [MyOtherClass]::static_variable_name. This just isn't how I'd prefer to do it.

Please advise

2
  • 1
    $file_location = Get-Variable myvar -ValueOnly Commented Apr 14, 2016 at 5:34
  • Do you have a resource that might explain why that works but $myvar will not? Also, if you create an answer with this, I can mark it. Thanks! Commented Apr 14, 2016 at 13:19

1 Answer 1

2

I can not provide reference right now, but I remember reading in some PowerShell blog, that purpose of this feature is to make PowerShell classes to be more self containing and to catch error early, for example, if you misspell variable name.

Parser simply disallow you to reference random variables in class method body directly, unless you prefix it with global or script scope. But, apparently, no technical restriction was made to prevent you from referencing variables in any other way.

So that, you can ask Get-Variable to read variable value for you:

Get-Variable myvar -ValueOnly 

And you even can make this, because nested script blocks are not analyzed:

&{$myvar} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.