.NET Framework - $args.count

Asked By IT Staff on 27-Dec-07 09:53 PM
if ($args.count -lt 4)
write-host "powershell.exe .\filegrp_day.ps1 <directory> <start-date >

i would like to script to accept only 3 or 4 parameters.

The line parameter <powergadget template> is optional. Those <directory>
How shld i go about that ?

Jeff replied on 29-Dec-07 12:36 AM
This is one way to do it:

$directory = $(throw "The directory parameter is required."),
$startDate = $(throw "The start date parameter is required."),
$endDate = $(throw "The end date parameter is required."),
$powerGadgetTemplate )

if ( $powerGadgetTemplate )
# template...
# no template...

Put this at the top of your script.  Using the param statement also
gives you the advantage of having named parameters.

IT Staff replied on 28-Dec-07 03:04 AM
thanks it works.

But the error looks so *messy* on the command prompt. Is there a way i can
put my own error msg only ?
Keith Hill [MVP] replied on 28-Dec-07 01:00 PM
Well you could go this route:

param($directory=$(Write-Host "Parameter -Directory is required";exit), ...)

However big caution here.  If you use this script from another script then
given the tweak above, if you don't supply a required parameter the script
will appear to have succeeded.  That is, it won't throw a terminating error
and $? will be True.

I often prefer to do this sort of parameter checking like this:

param($Directory, $StartDate, $EndDate, $PGTemplate)

function Usage {
FooScript -directory <string> -startDate <datetime> -endDate

-directory : Specifies the directory to blah
-startDate : Date to start ...
-endDate  : Date to end ...
-pgtemplate : path to template file
exit 1 # or throw here if you prefer

if (!$directory -or !$startDate -or !$endDate -or !$pgtemplate) {

... go on with script

That way you can give the user nice usage info.  Note that param() has to
appear before all other script so you can't call Usage from within the
param() statement.

Karl Prosser[MVP] replied on 28-Dec-07 01:14 PM
if you do not care about errors you do not have to use them either.