Monday, July 15, 2013

using throw inside param() block

Recently I had to write  a very restrictive script which takes few arguments like a filename, computername etc.
These parameters need to be compulsory otherwise the script should not run...

Below is the first function I came up with(nothing fancy):

function Test-AdvancedFunction {
     [CmdletBinding()]
      param(
           [Parameter(Position =0, Mandatory =$true )]
           [ValidateScript({Test-path $_})]
           [ System.String]
            $FileName

     )
     $Name
     ## Normal Script Code goes here
     }

In the above in the param() block a mandatory named argument is specified and has a ValidateScript attribute.

Everything looks great but the function needs to be very restrictive and it should fail when the parameter is not supplied to the function.
Right now because of making the parameter mandatory , I get a prompt to supply the value as below :



But I wanted my function to fail if the parameter is not specified cause I want to run my function non-interactively. 

I knew that the throw statement can be used to achieve this. Below is the info from about_throw topic.

USING THROW TO CREATE A MANDATORY PARAMETER

   You can use the Throw keyword to make a function parameter mandatory.

   This is an alternative to using the Mandatory parameter of the Parameter
   keyword. When you use the Mandatory parameter, the system prompts the user
   for the required parameter value. When you use the Throw keyword, the
   command stops and displays the error record.

So I used the throw statement to achieve what I needed, instead of the Mandatory Named Argument  :)

function Test-AdvancedFunction {
     [CmdletBinding()]
      param(
           [Parameter(Position =0 )]
           [ValidateScript({ Test-path $_})]
           [System.String]
           $FileName = $(throw "Filename not specified")

     )
      $FileName
      ## Normal Script Code goes here
     }


Now I can use validation as well as exit the function when the parameter is not specified  :

So in this way we can have a mandatory parameter which will exit the script/function if the parameter is not supplied while invoking the script/function rather than prompting user for the info.

No comments:

Post a Comment