关于脚本块About Script Blocks

简短说明Short description

定义脚本块的定义,并说明如何在 PowerShell 编程语言中使用脚本块。Defines what a script block is and explains how to use script blocks in the PowerShell programming language.

长说明Long description

在 PowerShell 编程语言中,脚本块是可用作单个单元的语句或表达式的集合。In the PowerShell programming language, a script block is a collection of statements or expressions that can be used as a single unit. 脚本块可以接受参数并返回值。A script block can accept arguments and return values.

从语法上讲,脚本块是括在大括号中的语句列表,如下面的语法所示:Syntactically, a script block is a statement list in braces, as shown in the following syntax:

{<statement list>}

脚本块以单个对象或数组形式返回脚本块中所有命令的输出。A script block returns the output of all the commands in the script block, either as a single object or as an array.

你还可以使用关键字指定返回值 returnYou can also specify a return value using the return keyword. return关键字不会影响或禁止从脚本块返回的其他输出。The return keyword does not affect or suppress other output returned from your script block. 不过, return 关键字退出该脚本块。However, the return keyword exits the script block at that line. 有关详细信息,请参阅 about_ReturnFor more information, see about_Return.

与函数一样,脚本块可以包含参数。Like functions, a script block can include parameters. 使用 Param 关键字分配命名参数,如以下语法所示:Use the Param keyword to assign named parameters, as shown in the following syntax:

{
Param([type]$Parameter1 [,[type]$Parameter2])
<statement list>
}

备注

在脚本块中,与函数不同,不能在大括号之外指定参数。In a script block, unlike a function, you cannot specify parameters outside the braces.

与函数一样,脚本块可以包含 DynamicParamBeginProcessEnd 关键字。Like functions, script blocks can include the DynamicParam, Begin, Process, and End keywords. 有关详细信息,请参阅 about_Functionsabout_Functions_AdvancedFor more information, see about_Functions and about_Functions_Advanced.

使用脚本块Using Script Blocks

脚本块是 Microsoft .NET 框架类型的实例 System.Management.Automation.ScriptBlockA script block is an instance of a Microsoft .NET Framework type System.Management.Automation.ScriptBlock. 命令可以具有脚本块参数值。Commands can have script block parameter values. 例如, Invoke-Command cmdlet 具有一个 ScriptBlock 采用脚本块值的参数,如以下示例中所示:For example, the Invoke-Command cmdlet has a ScriptBlock parameter that takes a script block value, as shown in this example:

Invoke-Command -ScriptBlock { Get-Process }
Handles  NPM(K)    PM(K)     WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----     ----- -----   ------     -- -----------
999          28    39100     45020   262    15.88   1844 communicator
721          28    32696     36536   222    20.84   4028 explorer
...

Invoke-Command 还可以执行具有参数块的脚本块。Invoke-Command can also execute script blocks that have parameter blocks. 使用 ArgumentList 参数按位置分配参数。Parameters are assigned by position using the ArgumentList parameter.

Invoke-Command -ScriptBlock { param($p1, $p2)
"p1: $p1"
"p2: $p2"
} -ArgumentList "First", "Second"
p1: First
p2: Second

前面的示例中的脚本块使用 param 关键字创建参数 $p1$p2The script block in the preceding example uses the param keyword to create a parameters $p1 and $p2. 字符串 "First" 绑定到) (第一个参数 $p1 ,而 "Second" 绑定到 ($p2) 。The string "First" is bound to the first parameter ($p1) and "Second" is bound to ($p2).

有关 ArgumentList 行为的详细信息,请参阅 about_SplattingFor more information about the behavior of ArgumentList , see about_Splatting.

您可以使用变量来存储和执行脚本块。You can use variables to store and execute script blocks. 下面的示例将一个脚本块存储在一个变量中,并将其传递给 Invoke-CommandThe example below stores a script block in a variable and passes it to Invoke-Command.

$a = { Get-Service BITS }
Invoke-Command -ScriptBlock $a
Status   Name               DisplayName
------   ----               -----------
Running  BITS               Background Intelligent Transfer Ser...

Call 运算符是执行存储在变量中的脚本块的另一种方法。The call operator is another way to execute script blocks stored in a variable. 与一样 Invoke-Command ,调用运算符执行子范围中的脚本块。Like Invoke-Command, the call operator executes the script block in a child scope. 调用运算符可使你更轻松地将参数用于脚本块。The call operator can make it easier for you to use parameters with your script blocks.

$a ={ param($p1, $p2)
"p1: $p1"
"p2: $p2"
}
&$a -p2 "First" -p1 "Second"
p1: Second
p2: First

您可以使用赋值将脚本块中的输出存储在变量中。You can store the output from your script blocks in a variable using assignment.

PS>  $a = { 1 + 1}
PS>  $b = &$a
PS>  $b
2
PS>  $a = { 1 + 1}
PS>  $b = Invoke-Command $a
PS>  $b
2

有关调用运算符的详细信息,请参阅 about_OperatorsFor more information about the call operator, see about_Operators.

将延迟绑定脚本块与参数一起使用Using delay-bind script blocks with parameters

一个类型化参数,该参数接受管道输入 (by Value) 或 (by PropertyName) 允许在参数上使用 延迟绑定 脚本块。A typed parameter that accepts pipeline input (by Value) or (by PropertyName) enables use of delay-bind script blocks on the parameter. 延迟绑定 脚本块中,可以使用管道变量引用对象中的管道 $_Within the delay-bind script block, you can reference the piped in object using the pipeline variable $_.

# Renames config.log to old_config.log
dir config.log | Rename-Item -NewName {"old_" + $_.Name}

在更复杂的 cmdlet 中,延迟绑定脚本块允许在对象中重复使用一个管道来填充其他参数。In more complex cmdlets, delay-bind script blocks allow the reuse of one piped in object to populate other parameters.

延迟时 的说明- 将脚本块绑定为参数:Notes on delay-bind script blocks as parameters:

  • 您必须显式指定任何用于 延迟绑定 脚本块的参数名称。You must explicitly specify any parameter names you use with delay-bind script blocks.

  • 参数不能是非类型化的,并且参数的类型不能为 [scriptblock][object]The parameter must not be untyped, and the parameter's type cannot be [scriptblock] or [object].

  • 如果在不提供管道输入的情况下使用 延迟绑定 脚本块,会收到错误。You receive an error if you use a delay-bind script block without providing pipeline input.

    Rename-Item -NewName {$_.Name + ".old"}
    
    Rename-Item : Cannot evaluate parameter 'NewName' because its argument is
    specified as a script block and there is no input. A script block cannot
    be evaluated without input.
    At line:1 char:23
    +  Rename-Item -NewName {$_.Name + ".old"}
    +                       ~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : MetadataError: (:) [Rename-Item],
          ParameterBindingException
        + FullyQualifiedErrorId : ScriptBlockArgumentNoInput,
          Microsoft.PowerShell.Commands.RenameItemCommand
    

另请参阅See Also

about_Functionsabout_Functions

about_Functions_Advancedabout_Functions_Advanced

about_Operatorsabout_Operators