将命令行参数传递给脚本的“内部”函数

时间:2015-03-12 19:39:58

标签: powershell powershell-v2.0

我有一个简单的PowerShell脚本:

# Foobar.ps1
Param(
    [parameter(Mandatory=$true)]
    [alias("i")]
    [String[]]
    $IDs,

    [parameter()]
    [alias("b")]
    [string]
    $Bar
)

Foreach ($ID in $IDs) {
    write-host $ID
}

write-host $Bar

PS> .\foobar -i 1234,5678 -b 'hello world'
1234
5678
hello world

我希望重构脚本以使用CmdletBinding的高级功能:

# Foobar.ps1
Function Invoke-Foo {

  [CmdletBinding()]
  Param(
      [parameter(Mandatory=$true)]
      [alias("i")]
      [String[]]
      $IDs,

      [parameter()]
      [alias("u")]
      [string]
      $Bar
  )

  Begin {}
  Process {
    Foreach ($ID in $IDs) {
        write-host $ID
    }
    write-host $Bar
  }
  End {}

}

# call internal function with command-line's arguments; only pass -b if it exists
Invoke-Foo -i <command line arg -i> -b <command line arg -b>

PS> .\foobar -i 1234,5678 -b 'hello world'
1234
5678
hello world

PS> .\foobar -i 111,222
111
222

如何正确捕获并将命令行参数传递给内部函数?

1 个答案:

答案 0 :(得分:0)

不确定这是否是最有效的解决方案,但似乎有效:

Foobar.ps1

# capture named arguments from command line
Param(
    [parameter(Mandatory=$true)]
    [alias("i")]
    [String[]]
    $IDs,
    [parameter()]
    [alias("b")]
    [string]
    $Bar
)

# internal function
Function Invoke-Foo {

  [CmdletBinding()]
  Param(
    [parameter(Mandatory=$true)]
    [alias("i")]
    [String[]]
    $IDs,
    [parameter()]
    [alias("b")]
    [string]
    $Bar
  )

  Begin {Write-Host 'Begin'}
  Process {
    Write-Host 'Process'
    Foreach ($ID in $IDs) {
        write-host $ID
    }
    If ($Bar) {write-host $Bar}
  }
  End {Write-Host 'End'}

}

# invoke internal function, supplying named arguments
Invoke-Foo -i $IDs -b $Bar