如何在 Windows PowerShell 中获取命令行参数

  1. 在 PowerShell 脚本中定义参数
  2. 在 PowerShell 脚本中使用命名参数
  3. 在 PowerShell 脚本中为参数分配默认值
  4. 在 PowerShell 脚本中使用开关参数
  5. 在 PowerShell 脚本中使用强制参数
如何在 Windows PowerShell 中获取命令行参数

我们使用名为 param() 的 Windows PowerShell 参数函数来处理参数。Windows PowerShell 参数函数是任何脚本的基本组成部分。参数是开发人员使脚本用户能够在运行时提供输入的方式。

在本文中,您将学习如何使用参数函数创建脚本、使用它们以及构建参数的一些最佳实践。

在 PowerShell 脚本中定义参数

管理员可以使用参数函数 param() 为脚本和函数创建参数。函数包含一个或多个由变量定义的参数。

Hello_World.ps1:

param(
    $message
)

然而,为了确保参数仅接受所需类型的输入,最佳实践是通过给参数分配数据类型来使用参数块 [Parameter()],并在变量前用方括号 [] 包住数据类型。

Hello_World.ps1:

param(
    [Parameter()]
    [String]$message
)

在上面的示例 Hello_World.ps1 中,变量 message 仅在传递的值具有数据类型 String 时才会接受该值。

在 PowerShell 脚本中使用命名参数

在脚本中使用参数函数的一种方法是通过参数名称——这种方法称为命名参数。当通过命名参数调用脚本或函数时,我们使用变量名称作为参数的全名。

我们在这个示例中创建了一个 Hello_World.ps1,并在参数函数内部定义了变量。请记住,我们可以在参数函数中放入一个或多个变量。

Hello_World.ps1:

param(
    [Parameter()]
    [String]$message,
    [String]$emotion
)

Write-Output $message
Write-Output "I am $emotion"

然后,我们可以在执行 .ps1 文件时将命名参数作为参数使用。

.\Hello_World.ps1 -message 'Hello World!' -emotion 'happy'

输出:

Hello World!
I am happy

在 PowerShell 脚本中为参数分配默认值

我们可以通过在脚本内部为参数赋值来预先分配一个值给参数。然后,运行脚本而不从执行行传递值,将采用脚本内部定义的变量的默认值。

param(
    [Parameter()]
    [String]$message = "Hello World",
    [String]$emotion = "happy"
)

Write-Output $message
Write-Output "I am $emotion"
.\Hello_World.ps1

输出:

Hello World!
I am happy

在 PowerShell 脚本中使用开关参数

我们可以使用的另一个参数是由 [switch] 数据类型定义的开关参数。开关参数用于表示二元或布尔值,以指示 truefalse

Hello_World.ps1:

param(
    [Parameter()]
    [String]$message,
    [String]$emotion,
    [Switch]$display
)
if ($display) {
    Write-Output $message
    Write-Output "I am $emotion"
}
else {
    Write-Output "User denied confirmation."
}

我们可以使用以下语法调用我们的脚本及其参数。

.\Hello_World.ps1 -message 'Hello World!' -emotion 'happy' -display:$false

输出:

User denied confirmation.

在 PowerShell 脚本中使用强制参数

在执行脚本时,通常需要一个或多个参数。我们可以通过在参数块 [Parameter()] 内部添加 Mandatory 属性来使参数成为强制参数。

Hello_World.ps1:

param(
    [Parameter(Mandatory)]
    [String]$message,
    [String]$emotion,
    [Switch]$display
)
if ($display) {
    Write-Output $message
    Write-Output "I am $emotion"
}
else {
    Write-Output "User denied confirmation."
}

当执行 Hello_World.ps1 时,Windows PowerShell 将不允许脚本运行,并提示您输入值。

.\Hello_World.ps1

输出:

cmdlet hello_world.ps1 at command pipeline position 1
Supply values for the following parameters:
message:
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn