0

我有这个代码片段。这个想法是在远程 pc 上调用调用命令,但如果命令失败,那么它应该重试。

代码如下所示:

Function Run-Command 
{
    param(

        [Parameter(Mandatory = $true)] 
        [Uri[]] $ConnectionUri,

        [Parameter(Mandatory = $true)] 
        [PSCredential] $Credential,

        [Parameter(Mandatory = $true)] 
        [ScriptBlock] $ScriptBlock,

        [Parameter(Mandatory = $true)] 
        [Int] $Time,

        [Parameter(Mandatory = $false)] 
        [Object[]] $ArgumentList

    )

    for($retry = 0; $retry -le 10; $retry++)
    {
      try
      {
        Invoke-Command -ConnectionUri $ConnectionUri -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList #-ErrorAction SilentlyContinue           
        if ($?)
        {
          break
        }

        Write-Verbose "Server is not ready yet . . . sleeping and trying again in $Time seconds."
        Start-Sleep -Seconds $Time
      }
      catch
      {
        Write-Verbose "Server is not ready yet . . . sleeping and trying again in $Time seconds."
        Start-Sleep -Seconds $Time
      }
    }

}

然后我应该能够像这样调用该函数:

Run-Command -ConnectionUri $ConnectionUri -Credential $Credential -ScriptBlock $SomeScriptBlock -Time 30

但由于某种原因,它并没有像我想象的那样工作。

提前致谢

问候马格努斯

4

1 回答 1

0

我想到了。对于任何有兴趣的人,这里是代码:

Function Run-Command 
{
    param(

        [Parameter(Mandatory = $true)] 
        [Uri[]] $ConnectionUri,

        [Parameter(Mandatory = $true)] 
        [PSCredential] $Credential,

        [Parameter(Mandatory = $true)] 
        [ScriptBlock] $ScriptBlock,

        [Parameter(Mandatory = $true)] 
        [Int] $Time,

        [Parameter(Mandatory = $false)] 
        $ArgumentList

    )

    for($retry = 0; $retry -le 10; $retry++)
    {
      try
      {

        if ($ArgumentList -eq $null)
        {
            Invoke-Command -ConnectionUri $ConnectionUri -Credential $Credential -ScriptBlock $ScriptBlock -ErrorAction SilentlyContinue
        }
        else
        {
            Invoke-Command -ConnectionUri $ConnectionUri -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -ErrorAction SilentlyContinue
        }

        if ($?)
        {
          break
        }

        Write-Verbose "Server is not ready yet . . . sleeping and trying again in $Time seconds."
        Start-Sleep -Seconds $Time
      }
      catch
      {
        Write-Verbose "Server is not ready yet . . . sleeping and trying again in $Time seconds."
        Start-Sleep -Seconds $Time
      }
    }
}

我怀疑它不起作用的原因是参数列表有时是空的。所以我添加了一个检查来决定运行哪个调用命令。

希望这可以帮助某人

/马格纳斯

于 2014-08-07T06:59:35.500 回答