我有这个代码片段。该想法正在远程PC上调用Invoke命令,但如果命令失败,则应重试。

代码如下所示:

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
.

但由于某种原因,它不起作用。

提前感谢

问候 MAGNUS

有帮助吗?

解决方案

我想出来了。对于任何感兴趣的人,这是代码:

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
      }
    }
}
.

我苏斯注意到它不起作用的原因是争论列表有时是空的。因此,我添加了一个检查以确定要运行的调用命令。

希望这段宫廷帮助某人

/ magnus

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top