I've seen this syntax on a variable before and not quite sure exactly what it is:
$script:Foo = "Bar"
To use the "Run with PowerShell" feature: In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.
PowerShell is one of the easiest languages to get started with and learn for multiple reasons. As mentioned before, PowerShell follows a "verb-noun" convention, which makes even more complex scripts easier to use (and read) than a more abstracted language like .
Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting.
The script:
prefix causes the name on the right hand side to be looked up in the script scope. Essentially data which is local to the script itself. Other valid scopes include global, local and private.
The help section for scope contains a bit of detail on this subject.
help about_Scopes
The syntax $script:Foo
is most commonly used to modify a script-level variable, in this case $Foo
. When used to read the variable, usually $Foo
is sufficient. For example rather than write this:
verbose-script.ps1
$script:foo = ''
function f { $script:foo }
I would write this (less verbose and functionally equivalent):
script.ps1
$foo = ''
function f { $foo }
Where $script:Foo
is crucial is when you want to modify a script-level variable from within another scope such as a function or an anonymous scriptblock e.g.:
PS> $f = 'hi'
PS> & { $f; $f = 'bye';$f }
hi
bye
PS> $f
hi
Notice that $f
outside the scriptblock did not change even though we modified it to bye
within the scriptblock. What happened is that we only modified a local copy of $f
. When you don't apply a modifier like script:
(or global:
), PowerShell will perform a copy-on-write
on the higer-scoped variable into a local variable with the same name.
Given the example above, if we really wanted to make a permanent change to $f
, we would then use a modifier like script:
or global:
e.g.:
PS> $f = 'hi'
PS> & { $f; $global:f = 'bye';$f }
hi
bye
PS> $f
bye
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With