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?
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With