PowerShell,使用没有值的参数调用脚本,就像带有选项的脚本一样

Kal*_*lle 18 powershell

是否可以使用选项调用PowerShell脚本?就像没有值的参数一样.

例如,我目前使用:

param (
    $lastmonth=0
);
Run Code Online (Sandbox Code Playgroud)

在脚本中.现在我可以使用这个电话了

script.ps1 -lastmonth 1
Run Code Online (Sandbox Code Playgroud)

要么

script.ps1 
Run Code Online (Sandbox Code Playgroud)

并使用$ lastmonth来控制流量.

但我想接听电话

script.ps1 -lastmonth
Run Code Online (Sandbox Code Playgroud)

script.ps1
Run Code Online (Sandbox Code Playgroud)

并根据是否给出-lastmonth来控制流量.

RB.*_*RB. 41

将参数类型设置为[switch],例如

param (
    [switch]$lastmonth
);
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,该变量将是一个布尔值.你可以测试它:

if ($lastMonth) {
    Write-Host "lastMonth is set."
}
else {
    Write-Host "lastMonth is not set."
}
Run Code Online (Sandbox Code Playgroud)

(谢谢克里斯)

  • ...然后它是一个布尔变量. (2认同)