传递cmdlet作为参数

时间:2015-03-20 17:54:23

标签: function powershell parameters cmdlets

我需要在powershell脚本中重启服务。问题是这个服务有点儿麻烦,经常需要关闭几次才能进入“停止”状态。因此我似乎无法使用Restart-Service cmdlet,而是需要重试Stop-Service cmdlet几次。这同样适用于启动服务。

所以我认为这是一个编写一个函数的好地方,它将采取一个动作(开始或停止)并重试几次直到它工作。问题是我不确定如何将操作作为参数传递。我可以将操作设为String,然后说if action == "start" do starcAction,但这不会很干净。有没有什么方法可以将Stop-Service这样的cmdlet作为参数传递?

2 个答案:

答案 0 :(得分:2)

对于您描述的场景,您通常会执行以下操作:

$maxTries = 5

switch ($args(0)) {
  'start' {
    Start-Service 'MySvc'
  }

  'stop' {
    $i = 0
    do {
      Stop-Service 'MySvc'
      $i++
    } until ((Get-Service 'MySvc').Status -eq 'Stopped' -or $i -ge $maxTries)
    if ((Get-Service 'MySvc').Status -ne 'Stopped') {
      Write-Error "Cannot stop service."
      exit 1
    }
  }

  default {
    Write-Error "Unknown action: $_"
    exit 1
  }
}

如果你真的想避免使用字符串参数,可以使用如下参数集:

[CmdletBinding(DefaultParameterSetName='none')]
Param(
  [Parameter(Mandatory=$true,ParameterSetName='start')]
  [Switch][bool]$Start = $false,
  [Parameter(Mandatory=$true,ParameterSetName='stop')]
  [Switch][bool]$Stop = $false
)

$maxTries = 5

switch ($PSCmdlet.ParameterSetName) {
  'start' {
    Start-Service 'MySvc'
  }

  'stop' {
    $i = 0
    do {
      Stop-Service 'MySvc'
      $i++
    } until ((Get-Service 'MySvc').Status -eq 'Stopped' -or $i -ge $maxTries)
    if ((Get-Service 'MySvc').Status -ne 'Stopped') {
      Write-Error "Cannot stop service."
      exit 1
    }
  }

  'none' {
    Write-Error "Usage: $($MyInvocation.MyCommand.Name) {-Start|-Stop}"
    exit 1
  }
}

答案 1 :(得分:1)

Param([Parameter(Mandatory)] [ValidateSet('Start','Stop')] [string] $Action)

这允许用户按Tab选择可能的值,并自动拒绝所有无效输入。

传入一个定义良好的参数(如果它是一个字符串,无关紧要)实际上比“传入一个命令行开关”更干净,如果有这样的话。