PowerShell Try/Catch retry loop re-executes a write command — how to keep retries idempotent?
0 reputation · 28 Mar 2020, 12:36 UTC
I am designing a retry wrapper in PowerShell (assume 7.x) around a command that writes data, using Try/Catch with -ErrorAction Stop so a transient failure lands in a single catch block. The concern is that a retry re-issues the same write, and I have no guarantee the first attempt actually failed before the error was raised — the write may have partially succeeded, so a blind retry could create a duplicate record.
The constraints: the target command does not expose a native idempotency key, so any deduplication has to happen in my script logic. I also want the retry path to log clearly, since a silent retry loop could mask an underlying error and leave the data in an unknown state. I am aware -WhatIf can preview side effects during testing, but that does not help at runtime.
My questions:
- What is the established pattern for making a PowerShell retry loop idempotent when the wrapped command has no built-in idempotency support — should deduplication be keyed on something like
$MyInvocation.MyCommand.Nameplus input parameters? - Is there a reliable way to distinguish "write never happened" from "write happened but the command reported an error afterward" from within a catch block?
- Does
ForEach-Object -ThrottleLimitmeaningfully help control retry frequency when writes are batched, or is it unrelated to idempotency?