Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Generic function to invoke PS code

$
0
0

I have written a custom PS function to allow me to execute a PS command in a loop for a certain amount of time. I need this because certain calls, to especially MS Exchange, have a habbit of sometimes timing out. The function is below. I wrote the function to avoid having to enclose code in the same redundant loop-code over and over.

It works on single line code, but not on blocks of code.

Can anyone point me in the right direction to 1) Get the same function to accept and execute blocks of code, or 2) or how I write another similar function that accepts and executes blocks of code?

---
function Invoke-CmdTimerLoop {
 param ($Cmd, $LogInfo = "Invoke-CmdTimerLoop", [switch]$LogExceptionsInLoop, $TimeoutSeconds = 30, $RetryIntervalMS = 500)
 Write-Debug -Message "$LogInfo : Timer started. Entering loop (TimeoutSeconds: $TimeoutSeconds, RetryInterval: $RetryIntervalMS ms)..."
 Write-Debug -Message "$LogInfo : Run Command: $Cmd"
 $timer = [diagnostics.stopwatch]::startnew()
 while ($timer.elapsed.totalseconds -lt $TimeoutSeconds) {
  try {
     Invoke-Expression -Command $Cmd
     $Exception=$null
     break
   }
   catch {
     $Exception = $_.Exception
     If ($LogExceptionsInLoop) { Write-SSDebug -Message "$LogInfo : Exception caught. Loop timer = $([Math]::Round($timer.Elapsed.TotalSeconds, 2)) seconds.`n`n$Exception" }
   }
   start-sleep -Milliseconds $RetryIntervalMS
 }
 $timer.stop()
 if($timer.elapsed.totalseconds -ge $TimeoutSeconds) {
  Write-Debug -Message "$LogInfo : did not run successfully within ($([Math]::Round($timer.Elapsed.TotalSeconds, 2)) seconds) seconds!" ; throw $Exception
 } Else {
    Write-Debug -Message "$LogInfo : Loop exited gracefully and timer stopped ($([Math]::Round($timer.Elapsed.TotalSeconds, 2)) seconds)"
  }
}
---

Examples of current usage:
---
Invoke-CmdTimerLoop -Cmd "Enable-Mailbox -Identity ""$Username"" -Alias ""$MailAlias"" -Database ""$MailboxDatabase"" -ErrorAction Stop"
Invoke-CmdTimerLoop -Cmd "Set-Mailbox -Identity $Username -OfflineAddressBook ""$CompanyNo Offline Address List"" -ErrorAction SilentlyContinue"
---

I would like to somehow define a block of code and feed that into the (or another) function that does the same.

Any great ideas for improvement?

Thanks!
Nicolaj


Viewing all articles
Browse latest Browse all 6937

Trending Articles