【问题标题】:Embedding parameters to a switch将参数嵌入开关
【发布时间】:2018-10-04 01:00:46
【问题描述】:

我有一个调用文件的 .ps1,如果它不能调用文件,它将在本地查找这些文件。我想提供一个选项,作为参数,在本地工作或从 Internet 获取,并指定要使用或调用 5 个文件中的哪一个。我使脚本与“本地”和“外部”函数一起工作,但我如何也向这些函数添加参数?

例如:

./script.ps1 -local file1,file2,file3

./script.ps1 -external file4,file5

这是我目前的代码:

Param(
    [Parameter(Position=1)][string]$option
)

function RunLocal {
    Write-Host "local"
}
function RunExternal {
    Write-Host "ext"
}
function RunDefault {
    Write-Host "default"
}

switch ($option) {
    local    { RunLocal }
    external { RunExternal }
    default  { RunDefault }
}

【问题讨论】:

标签: powershell parameter-passing powershell-2.0 powershell-3.0


【解决方案1】:

我会定义不同的parameter sets 并根据参数集名称进行区分。

[CmdletBinding(DefaultParameterSetName='default')]
Param(
    [Parameter(ParameterSetName='default', Position=0, Mandatory=$true)]
    [string[]]$Default,

    [Parameter(ParameterSetName='external', Position=0, Mandatory=$true)]
    [string[]]$External,

    [Parameter(ParameterSetName='local', Position=0, Mandatory=$true)]
    [string[]]$Local
)

# ...

switch ($PSCmdlet.ParameterSetName) {
    'local'    { RunLocal }
    'external' { RunExternal }
    'default'  { RunDefault }
}

# Usage:
# script.ps1 [-Default] 'file1', 'file2'
# script.ps1 -External 'file1', 'file2'
# script.ps1 -Local 'file1', 'file2'

另一个选项是对选项和文件列表使用单独的参数,正如 JPBlanc 建议的那样,但在这种情况下,您应该 validate -Option 参数,以便只能使用允许的选项:

[CmdletBinding()]
Param(
    [Parameter(Position=0, Mandatory=$true)]
    [ValidateSet('default', 'external', 'local')]
    [string]$Option,

    [Parameter(Position=1, Mandatory=$true)]
    [string[]]$File
)

# ...

switch ($Option) {
    'local'    { RunLocal }
    'external' { RunExternal }
    'default'  { RunDefault }
}

# Usage:
# script.ps1 'default' 'file1', 'file2'
# script.ps1 -Option 'default' -File 'file1', 'file2'
# script.ps1 'external' 'file1', 'file2'
# script.ps1 -Option 'external' -File 'file1', 'file2'
# script.ps1 'local' 'file1', 'file2'
# script.ps1 -Option 'local' -File 'file1', 'file2'

【讨论】:

  • 好的,很酷,所以在运行文件的情况下,我是否只需将它们设为函数?例如function RunLocal { function file1 {Write-Host "file1"}}
  • @Hausec 你为什么要这样做?这没有任何意义。
猜你喜欢
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 2011-02-09
  • 2012-04-07
  • 2021-08-16
  • 2021-10-31
相关资源
最近更新 更多