Home > other >  Retry command if condition is not match using powershell
Retry command if condition is not match using powershell

Time:10-08

Sorry for my bad english, i am not sure if my question is properly asked.

I want to run a powershell command if folder is empty: run it. if folder is not empty: do not run it. here is the basic script

If ((Get-ChildItem -Force "EMPTY FOLDER PATH") -eq $Null) {

RUN SOME COMMAND  
}
If ((Get-ChildItem -Force "EMPTY FOLDER PATH") -eq $Null) {

RUN SOME COMMAND  
}
If ((Get-ChildItem -Force "EMPTY FOLDER PATH") -eq $Null) {

RUN SOME COMMAND  
}

basically i will copy some file inside run some command. after copy move that file to somewhere and process it for some other kind of work.

now lets assume folder is not empty. script will run from start to last and end and no file will be copied.

i could use loop re-run the script. but in that case same file could be copied twice which i don't want.

if first command successfully execute and for second command if it see folder is not empty it will pause and run from that unsuccessful command again. i really don't know if it's possible or not.

CodePudding user response:

Use a loop with a retry counter, and keep retrying until the condition is met or the retry counter has been exhausted:

$retryCount = 3
while($retryCount--){
  if(Get-ChildItem -Force "EMPTY FOLDER PATH"){
    # found items in folder, break out of retry loop
    break
  }

  # Run command
  CommandToRun

  if($retryCount -eq 0 -and -not(Get-ChildItem -Force "EMPTY FOLDER PATH")){
    # out of retries and still no luck, time to stop trying
    Write-Error "Exceeded retries for CommandToRun"
    return
  }
}
  • Related