Convenient Way of Restarting Powershell at a Functional Step

If you happen to have a Powershell script which contains several or more major functional processes, you may find your self having to restart your process at a particular process. With scripting, it is usually relatively easy to “rip” out the steps you need to rerun after a crash and then just run those steps. In fact, you may even end up creating a new script for each functional process.

I have a multi-step process which must run daily. The entire process is very fragile and can experience problems in any of the steps it performs. I’ve been able to identify and circumvent many of the problems but it can still break in various sections. Because each functional process is long running, I need to be able to restart the process at any of the functional steps and continue from there.

The easiest way for me to accomplish this is by using a Param in conjunction with a ‘Switch’ statement. The Param identifies which function you want to start with, a Hashtable is used to convert the  identifier to a number, and a Switch statement wraps all the functions. Because the nature of a Switch statement is to continue testing values after finding the first one (unless you include a Break), you can effectively begin at a point and continue processing each function.

My example is seriously scaled down version but I believe it conveys the idea. The functional areas of my process are:

  1. Download – I have to download a file from a vendor FTP site
  2. Decrypt – the downloaded file needs to be decrypted
  3. Extract – the decrypted file is a Zip and I need to extract the contents
  4. Format – I have to reconstruct an entire Database using SQL files contained in the Zip extraction. The existing database is deleted, created, and structures added.
  5. Import – BCP is used to load the database tables with data from files in the Zip extract.

Here is the example

	[Parameter(Position=0, Mandatory=$false)]
	[string]$StartAt = "Download"
#requires –Version 2.0
Set-StrictMode -Version "Latest"
# Equate our StartWith parameter with a hashtable
$step = @{Download = 1; Decrypt = 2; Extract = 3; Format = 4; Import = 5}

	1 { Write-Output "Download function will run" }
	{$_ -le 2} { Write-Output "Decrypt Function will run" }
	{$_ -le 3} { Write-Output "Extract Function will run" }
	{$_ -le 4} { Write-Output "Format Function will run" }
	{$_ -le 5} { Write-Output "Import Function will run" }

Leave a Reply