Writing Scripts, Reusing Functionality

When you want to start packaging and reusing your commands, the best place to put them is in scripts and functions. A script is a text file that contains a sequence of PowerShell commands. A function is also a sequence of PowerShell commands but is usually used within a script to break it into smaller, more easily understood segments.

Writing Scripts

To write a script, write your PowerShell commands in a text editor and save the file with a .PS1 extension.

Running Scripts

There are two ways to execute a script: by invoking it or by dot-sourcing it.

Invoking

Invoking a script runs the commands inside it. Unless explicitly defined with the GLOBAL scope keyword, variables and functions defined in the script do not persist once the script exits.

You invoke a script by using the invoke/call operator (&) with the script name as the parameter:

& "C:Script DirectoryRun-Commands.ps1" <Parameter List>

You can use either a fully qualified path or a path relative to the current location. If the script is in the current directory, you must explicitly say so:

.Run-Commands.ps1 <Parameter List>

If the path contains no spaces, you may omit both the quotes and invoke operator.

Dot-sourcing

Dot-sourcing a script runs the commands inside it. Unlike invoking a script, variables and functions defined in the script do persist after the script exits.

You invoke a script by using the dot operator (.) with the script name as the parameter:

. "C:Script DirectoryRun-Commands.ps1" <Parameter List>

You can use either a fully qualified path, or a path relative to the current location. If the script is in the current directory, you must explicitly say so:

. .Run-Commands.ps1 <Parameter List>

If the path contains no spaces, you may omit the quotes.

Note

By default, a security feature in PowerShell called the Execution Policy prevents scripts from running. To understand the different execution policies available to you, type get-help about_signing. After selecting an execution policy, use the Set-ExecutionPolicy cmdlet to configure it:

Set-ExecutionPolicy RemoteSigned

Providing Input to Scripts

PowerShell offers several options for processing input to a script.

Argument array

To access the command-line arguments by position, use the $args array that is available to all scripts:

$firstArgument = $args[0]
$secondArgument = $args[1]
$argumentCount = $args.Count

Formal parameters

param([<TypeName>] $variableName = <Default Value>, ...)

Formal parameters allow you to benefit from some of the many benefits of PowerShell’s consistent command-line parsing engine.

PowerShell exposes your parameter names (i.e.: $variableName) the same way that it exposes parameters in cmdlets. Users need only to type enough of your parameter name to disambiguate it from the rest of the parameters. If the user does not specify the parameter name, PowerShell attempts to assign the input to your parameters by position.

If you specify a type name, PowerShell ensures that the user input is of that type. If you specify a default value, PowerShell uses that value if the user does not provide input for that parameter.

Tip

To make a parameter mandatory, define the default value so that it throws an error:

param($mandatory = $(throw "Please input the mandatory parameter."))

Pipeline input

To access the data being passed to your cmdlet via the pipeline, use the $input enumerator available to all scripts:

foreach($element in $input)
{
   "Input was: $element"
}

The $input variable is a .NET enumerator over the pipeline input. Enumerators support streaming scenarios very efficiently but do not allow you to access arbitrary elements as you would with an array. If you want to process their elements again, you must call the Reset() method on the $input enumerator once you reach the end.

If you need to access the pipeline input in an unstructured way, the following command converts the input enumerator to an array:

$inputArray = @($input)

Cmdlet keywords in scripts

When pipeline input is a core scenario of your script, you may include statement blocks labeled begin, process, and end:

param(…)

begin
{
  …
}
process
{
  …}
end
{
  …}

PowerShell executes the begin statement when it loads your script, the process statement for each item passed down the pipeline, and the end statement once all pipeline input has been processed. In the process statement block, the $_ variable represents the current pipeline object.

When you write a script that includes these keywords, all of the commands in your script must be contained within the statement blocks.

$MyInvocation automatic variable

The $MyInvocation automatic variable contains information about the context under which the script was run, including detailed information about the command (MyCommand), the script that defines it (ScriptName), and more.

Retrieving Output from Scripts

Pipeline output

<any command>

The return value/output of a script is any data that the scripts writes to the pipeline. If a script contains the commands,

"Text Output"
5*5

then assigning the output of that script to a variable creates an array with the two values, Text Output and 25.

Return statement

return <value>

The statement,

return $false

is simply a short form for pipeline output:

$false
return

Exit statement

exit <errorlevel>

The exit statement returns error codes. It sets the $LastExitCode automatic variable to <errorLevel>, which sets the $? automatic variable to $false when <errorLevel> is greater than zero.

Tip

See the “PowerShell Automatic Variables” appendix for more information about automatic variables.

Functions

function SCOPE:<function name>(parameter declaration)
{
   <statement block>}

or:

filter SCOPE:<function name>(parameter declaration)
{
   <statement block>
}

Functions allow you to package blocks of closely related commands into a single unit that you can access by name.

Valid scope names are: global (to create a function available to the entire shell,) script (to create a function available only to the current script,) local (to create a function available only to the current scope and subscopes,) and private (to create a function available only to the current scope.) The default scope is the current scope.

The content of a function’s statement block follows the same rules as the content of a script. Functions support the $args array, formal parameters, the $input enumerator, cmdlet keywords, pipeline output, and equivalent return semantics.

The parameter declaration, as an alternative to a param statement, follows the same syntax as the formal parameter list, but does not require the param keyword.

A filter is simply a function where the statements are treated as though they are contained within a process statement block.

Tip

Commands in your script can access only functions that have already been defined. This can often make large scripts difficult to understand when the beginning of the script is composed entirely of helper functions. Structuring a script in the following manner often makes it more clear:

function Main
{
   (...)
   HelperFunction
   (...)
}

function HelperFunction
{
   (...)
}

. Main

As with a script, you may either invoke or dot-source a function.

Script Blocks

$objectReference =
{
   <statement block>
}

PowerShell supports script blocks, which act exactly like unnamed functions and scripts. Like both scripts and functions, the content of a script block’s statement block follows the same rules as the content of a function or script. Script blocks support the $args array, formal parameters, the $input enumerator, cmdlet keywords, pipeline output, and equivalent return semantics.

As with both scripts and functions, you may either invoke or dot-source a script block.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.229.113