使用PowerShell实现多人IFs的更好方式

使用PowerShell实现多人IFs的更好方式,powershell,Powershell,我想知道我是以最好的方式解决这个问题,还是有更好的方式完成我的任务 我在PowerShell中编写了一个函数,该函数使用不同的参数,但有些参数不能一起工作 例如,如果我正在运行函数并指定computerName参数,那么我也不能传递多个计算机名的列表 我知道我可以像If($computerName)-和($computerList)){Then write and error}一样编写多个If语句 但是有几个参数,而不仅仅是两个,所以我是否需要为每一组可以输入的参数做一个if,或者是否有更好的方

我想知道我是以最好的方式解决这个问题,还是有更好的方式完成我的任务

我在PowerShell中编写了一个函数,该函数使用不同的参数,但有些参数不能一起工作

例如,如果我正在运行函数并指定computerName参数,那么我也不能传递多个计算机名的列表

我知道我可以像If($computerName)-和($computerList)){Then write and error}一样编写多个If语句

但是有几个参数,而不仅仅是两个,所以我是否需要为每一组可以输入的参数做一个if,或者是否有更好的方法来解决这个问题


目前我有多个If,比如If$computerName-和!(日志文件)和$computerlist),然后写入一个错误等。

这里的PowerShell惯用解决方案是声明一个参数,该参数接受以下任一项:

现在用户可以同时做这两件事

Get-Stuff -ComputerName oneComputerName
。。。及

"many","computer","names" |Get-Stuff
或者就这件事而言

$computers = Get-Content .\Computers.txt
Get-Stuff -ComputerName $computers
# or
$computers |Get-Stuff

我知道我可以写多个
If
语句,就像
If($computerName)-和($computerList)){Then write and error}

可以,但这通常不是一个好主意-最好通过自动变量
$PSBoundParameters
测试参数值是否传递给参数:

function Get-Stuff
{
  param(
    [string]$AParameter,
    [string]$ADifferentOne
  )

  if($PSBoundParameters.ContainsKey('AParameter')){
    # an argument was definitely provided to $AParameter
  }

  if($PSBoundParameters.ContainsKey('ADifferentOne')){
    # an argument was definitely provided to $ADifferentOne
  }
}

“我如何声明和使用互斥参数”这一隐含问题的答案是:

PowerShell现在可以识别两个不同的参数集,每个参数集只接受我们的一个参数:

PS ~> Get-Command Verb-Noun -Syntax

Verb-Noun -ComputerName <string> [<CommonParameters>]

Verb-Noun -ComputerList <string[]> [<CommonParameters>]
PS~>Get命令动词名词-语法
动词名词-ComputerName[]
动词名词-ComputerList[]

用于声明互斥参数。是的,我曾想过这样做,但id编写函数的方式是这样的,如果提供了计算机(即文本文件),那么他们必须指定日志文件路径和可选的输出文件路径,然而,对于一台计算机,则不需要日志文件,也不需要输出文件,因为它只是在屏幕上显示输出……但后来意识到这样做,我需要大量的if语句来检查他们在命令中输入的参数line@deniscooper我用一个如何检查的例子更新了答案
$PSBoundParameters
代替变量本身,可能也很有用。这看起来不错,我以前没有见过,所以请看一看,看看我是否可以让它工作。谢谢你的提示!我只是想说参数集完全符合我的要求,谢谢
function Verb-Noun
{
  param(
    [Parameter(Mandatory = $true, ParameterSetName = 'SingleComputer')]
    [string]$ComputerName,

    [Parameter(Mandatory = $true, ParameterSetName = 'MultipleComputers')]
    [string[]]$ComputerList

  )

  if($PSCmdlet.ParameterSetName -eq 'SingleComputer'){
    # just one, we can deal with $ComputerName
  }
  else {
    # we got multiple names via $ComputerList
  }

}
PS ~> Get-Command Verb-Noun -Syntax

Verb-Noun -ComputerName <string> [<CommonParameters>]

Verb-Noun -ComputerList <string[]> [<CommonParameters>]