View Single Post
Old 06-27-2008   #4 (permalink)
Shay Levi


 
 

Re: Strategy for handling parameters to a script

Hi Jacob,


For Powerhell parameters use '-parameterName value' instead of '/parameterName:value'

There are several ways to define/validate a parameter inside a script/function
and . Basically to find out if a parameter has a value:

param ($foo)
if($foo) { 'param $foo has a value' } else {'no value found for $foo'}



You can initialize the parameter with a default value (if no value supplied
by the caller):

param ( $foo = "defaultFooValue")



The default value for switch parameter is $false. When the caller specifies
the parameter then PowerShell sets the value to $true.

param ( [switch]$foo )
if($foo) { 'the caller specified $foo, do something...'}


Make $foo mandatory (throw error if no value has been specified):
param ( $foo = $(throw 'must have a value')


Using parameter types, convert the parameter to a type of your choice. If
possible, PowerShell convert the value to the specific type otherwise the
user gets an error.
param ( [string]$foo)


Must be a number and have a value (an error is thrown if the value is not
a number):
param ( [int]$foo = $(throw 'must be a number')



Handling parameters is a mixture of all above methods.





---
Shay Levi
$cript Fanatic
http://scriptolog.blogspot.com

JN> Hey,
JN>
JN> perhaps I should supply an example.
JN>
JN> Let's say TestScript had 10 possible parameters you could pass to
JN> it.
JN>
JN> E.g. "TestScript /whatever:0 /morewhatever:4
JN> /evenmorewhatever:hellno" and so forth.
JN>
JN> How do you:
JN>
JN> 1. Best make the script do what it should do, based on the values in
JN> those
JN> parameters
JN> 2. Any difference to using /command, -command or something else ?
JN> Does PS
JN> require something particular here ?
JN> 3. How do you best make the script avoid the parameters NOT set ?
JN> E.g. in
JN> the above example, 7 are missing of the 10 - how do you stick to the
JN> script
JN> JUST using the 3 that are used ?
JN> I'm looking for any and all ways to do it, since it's simply for
JN> inspiration for finding a way that works (for me), and I was kinda
JN> wondering
JN>
JN> Best Regards,
JN> Jacob Saaby Nielsen
JN> http://www.ijacob.info
JN> gmail: jacob DOT saaby
JN> hotmail (IM/LinkedIN/Facebook): same as gmail
Quote:
Quote:

>> Hey guys,
>>
>> anyone got any good way to handle parameters to a script ?
>>
>> E.g. the script takes certain parameters.
>> What's the best way to check if they're set, and if they are to use
>> them,
>> if they're not, how to not use them.
>> Anybody did something they wanna share in that regard ?
>> I'm thinking something that builds a command, but there might be a
>> much better way.
>>
>> Please share how you accomplish this
>>
>> Best Regards,
>> Jacob Saaby Nielsen
>> http://www.ijacob.info
>> gmail: jacob DOT saaby
>> hotmail (IM/LinkedIN/Facebook): same as gmail

My System SpecsSystem Spec