Utilisation de la commande invoke dans une fonction
-
21-12-2019 - |
Question
J'ai cet extrait de code.L'idée appelle une commande invoquée sur un PC distant, mais si la commande échoue, elle devrait réessayer.
Le code ressemble à ceci:
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
}
}
}
Je devrais alors pouvoir appeler la fonction comme suit:
Run-Command -ConnectionUri $ConnectionUri -Credential $Credential -ScriptBlock $SomeScriptBlock -Time 30
Mais pour une raison quelconque, cela ne fonctionne pas comme je le pensais.
Merci d'avance
Cordialement Magnus
La solution
Je l'ai compris.Pour toute personne intéressée, voici le code:
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
}
}
}
Je ressactionne la raison de ne pas travailler était que l'argumentListe était parfois vide.J'ai donc ajouté un chèque pour décider qui invoquez-la commande à exécuter.
J'espère que ce migth aide quelqu'un
/ magnus
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow