Skip to content

Instantly share code, notes, and snippets.

@twofingerrightclick
Last active February 4, 2023 00:13
Show Gist options
  • Save twofingerrightclick/298dc363662196247ad43cccbdf0a367 to your computer and use it in GitHub Desktop.
Save twofingerrightclick/298dc363662196247ad43cccbdf0a367 to your computer and use it in GitHub Desktop.
Learn a bit about variables in PowerShell by running this script
function Name {
#what is the output here?
write-host $name # $name is "foo" because it is the global variable $name
$name = "bar" #the global $name cannot be modified here and so this is actually creating
# a local variable, same as $local:name = "bar".
# in other words it will create a local variable if you try to modify a variable in a child scope
# what is the output here?
write-host $name # so now $name is implied to be the $local one (because a $local:name exists) and not the $script one is "bar"
# powershell will get the local variable if it exists, otherwise it will get the script variable otherwise the global variable...
#what is the output here?
write-host $script:name
#that was easy how about this?
$script:name = "hello"
#what is the output here?
write-host $global:name
# thats because Script scope is the nearest ancestor script file's scope or Global if there is no nearest ancestor script file.
}
$name = "foo" # global variable
#welcome to powershell
#1. children (functions, scripts, modules, etc) can access variables in the parent scope, but cannot modify them
# powershell will create a local variable if you try to modify a variable in a child scope
Name
# 2. variables are case in-sensitive and not typed unless you use the [type] syntax
$count = 0;
$count = "not a number";
#what is outputed here?
write-host $Count
# 3. variables are persistent through a powershell session!
[int]$count = 0;
#you wont be able to run this script a second time without restarting powershell
# because count is now typed as an int
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment