Referring to variables created in a function
PowerShell — Understanding Scope - by Rod Trent - myITforum
Question about scopes and best practices
Scope Variable usage
Videos
about_Scopes
So we have three main scopes, from the looks of things:
-
global
-
local
-
script
I think I understand local; if you do not define a scope, the scope is defaulted to local. I think? Meanwhile, global is accessible to the whole session. I think?
In the context of functions, by default, any variable defined within a function is inaccessible outside of the function. You use return to pass data out of the function.
But, if you declare a variable outside the function with the global scope, you can access it within a function. I’ve used this to declare HashTables and Lists outside the function, and then add elements to the HashTable or List within a function.
Or, if you declare a variable with the global scope within a function, it will also be accessible outside the function. It’s not how I would do things, but a colleague made a pair of functions in a script to connect and disconnect from a database. He declared the database details and credentials at the top of the script using the global scope, and then created the connection within the connection function with the global scope. This allowed him to call the same connection variable in the disconnect function to close the connection. I’d have probably defined the connection outside of the connect function …
But, if I have all my code contained within one script, do I need to use the global scope to make variables accessible inside and outside of functions? Would the script scope work? The explanation in the link at the top suggests it wouldn’t work …
What is this best practice?