【问题标题】:How to prompt for $args when missing丢失时如何提示输入 $args
【发布时间】:2016-04-26 08:17:21
【问题描述】:

我的脚本:

$computername=$args[0]
if ($args -eq $null) { $computername = Read-Host "enter computer name" }
Get-ADComputer -Id $computername -Properties * | select name,description

如果我通过脚本传递参数,即:

get-ComputerName.ps1 computer01

它工作正常。但是,如果我跳过计算机,我希望它提示我,但我会收到此错误:

Get-ADComputer:无法验证参数“身份”上的参数。论据
一片空白。为参数提供一个有效值,然后尝试运行
再次命令。
在 U:\get-ADComputer-assigned-user.ps1:9 char:20
+ 获取 ADComputer -Id $computername -Properties * |选择名称,描述
+ ~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Get-ADComputer], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

我不知道如何使它工作。

【问题讨论】:

标签: powershell args


【解决方案1】:

不要使用automatic variable$args,而是为计算机名定义一个特定的强制参数:

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true, Position=0)]
  [string]$ComputerName
)

Get-ADComputer -Id $ComputerName -Properties * | Select-Object Name, Description

这将允许您像这样运行您的脚本:

./Get-ComputerName.ps1 -ComputerName computer01

或者像这样:

./Get-ComputerName.ps1 computer01

如果缺少参数,系统会提示您输入:

PS C:\> ./Get-ComputerName.ps1

cmdlet test.ps1 at command pipeline position 1
Supply values for the following parameters:
ComputerName: _

如果您希望脚本抛出错误而不是提示缺少参数,您可以这样做:

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$false, Position=0)]
  [string]$ComputerName = $(throw 'Parameter missing!')
)

Get-ADComputer -Id $ComputerName -Properties * | Select-Object Name, Description

Check the documentation 了解有关 PowerShell 中参数处理的更多信息。

【讨论】:

    【解决方案2】:

    似乎 $args 将永远存在,因此 ($args -eq $null) 将永远为 false。要查看 $args 是否为空,您可以这样做

    if ($args.Length -eq 0)
    

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 2017-08-09
      • 2015-08-17
      • 1970-01-01
      相关资源
      最近更新 更多