I am working on a set of functions to perform and validate a wide variety of actions. For instance, I don't just want to create a folder. I want to validate that it was created after I run my function. If it's not, I want to be sure it's clear what failed and why. The best general pattern I can come up with for this is as follows:
function Do-Something
{
param(
someparams
)
if(whatINeedtoDoIsAlreadyDone)
{
Write-Host "What you're trying to do it already done.";
}
else
{
try
{
Do-Whatever -params param
}
catch [System.Exception]
{
Write-Host "Problemo"
}
finally
{
Validate-WhatIDid
Clean-Up
}
}
}
With a practical example, here is a Create-File function I wrote with a Time-Stamp function used to shorten DateTime writing:
function Time-Stamp
{
return [System.DateTime]::Now.ToString("yyyy.MM.dd hh:mm:ss");
}
function Create-File
{
param(
[parameter(Mandatory=$true)]
[string]
$filePath,
[parameter(Mandatory=$true)]
[string]
$fileName,
[parameter(Mandatory=$false)]
[string]
$fileContent
)
# Combine filePath and fileName.
if($filePath.EndsWith(""))
{
$file = "$filePath$fileName";
}
else
{
$file = "$filePath$fileName";
}
# Check to see if file already exists
if([System.IO.File]::Exists($file))
{
# Notify host file already exists.
Write-Host "$(Time-Stamp): $file already exists.";
}
else
{
# Attempt to create file.
Try
{
# Notify host of file creation
Write-Host "$(Time-Stamp): Creating file: $file.";
# Create file
if(!$fileContent)
{
$fileStatus = New-Item -Path $filePath -Name $fileName -ItemType File;
}
else
{
$fileStatus = New-Item -Path $filePath -Name $fileName -ItemType File -Value $fileContent;
}
}
# Catch exceptions
Catch [System.Exception]
{
# Notify host of exception
Write-Host "$(Time-Stamp): Error creating file $file.";
}
Finally
{
# Validate file was created
Write-Host "$(Time-Stamp): Validating file $file was created.";
if([System.IO.File]::Exists($file))
{
Write-Host "$(Time-Stamp): $file was created.";
}
else
{
Write-Host "$(Time-Stamp): $file was not created.";
}
}
}
}
What other sanity checks would you add to make sure that problems are handled. I am thinking about adding a line to each section that will switch a global variable called $continueProcessing to $false if some portion of the function fails so I don't waste time continuing with a script that has errors at any given checkpoint.