Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does script: do in powershell?

Tags:

powershell

I've seen this syntax on a variable before and not quite sure exactly what it is:

$script:Foo = "Bar"
like image 277
Micah Avatar asked Dec 01 '10 23:12

Micah


People also ask

How do I run a script in PowerShell?

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.

Is PowerShell scripting easy?

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 .

What language is PowerShell script?

Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting.


2 Answers

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
like image 21
JaredPar Avatar answered Oct 24 '22 15:10

JaredPar


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
like image 175
Keith Hill Avatar answered Oct 24 '22 15:10

Keith Hill