Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason not to throw an ArgumentException in a powershell param() block?

Tags:

powershell

I was looking for a way to make required parameters in powershell when I discovered this blog post suggesting I do the following:

param(
    [string] $ObjectName = $(Throw "Parameter -ObjectName must be set to the name of a database object")
);

After digesting for a while I came to the conclusion that it might be better to throw an ArgumentException as opposed to a string:

param(
    [string] $ObjectName = $(Throw New-Object System.ArgumentException "Parameter -ObjectName must be set to the name of a database object","ObjectNamt")
);

Now from a C# point of view the latter would be better. Is there any reason this practice does not translate in powershell?

like image 946
Justin Dearing Avatar asked Mar 26 '11 18:03

Justin Dearing


1 Answers

In PowerShell 2.0 you can mark the parameter as Mandatory and let PowerShell do the work for you:

Param(
    [Parameter(Mandatory=$true,
        Position=0,
        HelpMessage='ObjectName must be set to the name of a database object')]
    [string]
    $ObjectName
)
like image 80
Shay Levy Avatar answered Nov 03 '22 16:11

Shay Levy