PowerShell 参数上的多个值

  1. 理解 PowerShell 中的 Parameter 函数
  2. 在 PowerShell 中使用 命名 参数
  3. 在 PowerShell 中对参数使用默认值
  4. 在 PowerShell 中使用 Switch 参数
  5. 在 PowerShell 中使用 Mandatory 参数
  6. 在 PowerShell 中使用未知数量的参数
  7. 在 PowerShell 中使用管道参数
PowerShell 参数上的多个值

我们使用 PowerShell 参数函数 param 处理参数。它是任何脚本的基本组成部分,使开发人员能够在运行时提供输入。

此外,如果脚本的行为需要更改,参数可以提供一个机会来实现这一点,而无需更改底层代码。

本文将讨论 parameter 函数、我们可以定义的不同变量、在单个参数中处理多个值以及示例用法。

理解 PowerShell 中的 Parameter 函数

管理员可以使用参数函数 param() 为脚本创建参数。

在内部,参数函数包含一个或多个由变量定义的参数。

param ($myVariable)

但是,为了确保参数仅接受所需的输入类型,最好通过在变量前用方括号 [] 括住数据类型来为参数分配数据类型。

param ([String]$myVariable)

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

powershell.exe .\sample.ps1 -name "John"

在 PowerShell 中对参数使用默认值

我们可以通过在脚本中给参数赋值来预先分配一个默认值。

此外,执行脚本而不从命令行传递值将采用脚本内定义的默认变量。

param ([String]$name = "John")

在 PowerShell 中使用 Switch 参数

我们可以为我们的脚本使用另一种参数类型:由 [switch] 数据类型定义的 switch 参数。

此参数主要用于我们之前讨论的二进制或布尔值,表示值为 truefalse

param ([switch]$isEnabled)

示例代码:

"This string is from the pipeline." | .\pipeline.ps1

输出:

This string is from the pipeline.

使用这种技术为运行链式 PowerShell 文件打开了许多机会。

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