Friday, January 28, 2011

Validating Command Line Parameters

A common reason I write scripts is to provide other members of my IT community the ability to perform functions that standard tools cannot satisfy. Many of these scripts require multiple parameters in order to return the desired result. The last thing I want to do is take to time to explain why something I wrote failed to provide the desired result because of an input error. Human error when someone else is using your work should be forefront in your mind. Evaluating the parameters supplied to a script and making sure that they meet a certain level of sanity reduces those chances.

You can do basic checking directly in the param using Read-Host but that just insures a value is provided.
param([string]$path = $(Read-Host -prompt "`tPath"))
This will not guarantee that the data the script is expecting will be provided by the user nor can it provide confirmation that it is what the user meant. This can be very crucial when dealing with scripts that may delete or modify objects. Sometimes, you may even want to go the extra mile and ask, "Are you really sure?". The following code is a typical interrogation I would do when asking for a path to be supplied.
param([string]$path)

if(![bool]$path) {
 Write-Host "You are missing the `"-path`" command line argument" -foregroundColor Red
 Write-Host ""
 Write-Host "This is the path that the script requires to perform its function."
 Write-Host ""
 while((![bool]$path)) {
  $path = Read-Host -prompt "`tPath"
 }
 Write-Host ""
}
if(!(Test-Path -path $path)) {
 Write-Host "Unable to locate: $path" -foregroundColor Red
 Write-Host ""
 Write-Host "Please review the correct path"
 Write-Host ""
 while(!(Test-Path -path $path)) {
  $path = Read-Host -prompt "`tPath"
 }
 Write-Host ""
}

$answer = $null
while($answer -ne "Y" -and $answer -ne "N") {
 $answer = Read-Host -prompt "Are you sure you want to use $path (Y/N)?"
}

if($answer -eq "N") {
 Write-Host ""
 Write-Host "Quiting..." -foregroundColor Yellow
 exit
}

Write-Host ""
Write-Host "`$path = $path"

No comments:

Post a Comment