我有这段代码。想法是在远程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
但由于某种原因,它不能像我想象的那样起作用。
提前致谢
此致 马格努斯
答案 0 :(得分: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
}
}
}
我怀疑它不起作用的原因是参数列表有时是空的。所以我添加了一个检查来决定运行哪个Invoke命令。
希望这次迁移帮助某人
/马格努斯