Script Blocks


A script block is a series of PowerShell statements enclosed in curly braces. A script block can be assigned to a variable as shown here:

 PS C:\> $sb = { >> $x = 10 >> $y = 10 >> $x * $y } >> 

Note that this script was typed interactively. When it saw the {character, PowerShell knew we were typing a script block. The special >> prompt indicated that PowerShell was waiting for additional input. Pressing Enter on a blank >> prompt ended the input. You can prove that the script block text is in the $sb variable by checking it as follows:

 PS C:\> $sb $x = 10 $y = 10 $x * $y PS C:\> 

The script block can be executed with the invoke operator, which is an ampersand (&):

 PS C:\> &$sb 100 PS C:\> 

When invoked as part of a pipeline, a script block has access to a special variable called $input that contains all of the objects passed through the pipeline. For example, the Get-Process cmdlet returns an object for each running process. These objects are all stored in $input and can be enumerated with a foreach construct:

 PS C:\> $sb = { >> foreach ($process in $input) { >> $process.ProcessName } >> } >> PS C:\> get-process | &$sb acrotray alg ati2evxx ati2evxx BTSTAC~1 BTTray btwdins csrss dllhost explorer firefox Groove Hpqgalry 

Again, this was all typed interactively. Notice that when the Get-Process is called its output is piped to $sb, which was invoked using the & operator. This may be clearer in the following script:

Blocktest.ps1

image from book
 $sb = {   foreach ($process in $input) {     $process.ProcessName   } } get-process | &$sb 
image from book

Running this script produces the same output:

 PS C:\> test\blocktest acrotray alg ati2evxx ati2evxx BTSTAC~1 BTTray btwdins csrss dllhost explorer firefox Groove Hpqgalry 

Script blocks are a simple way to modularize code and allow it to be reused. However, script blocks become more important when used in conjunction with other modularization techniques such as functions and filters.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net