Monday, December 18, 2017

How To Create PowerShell Function Mandatory Parameter Value

Overview

PowerShell functions are helpful in saving time when you have repetitive task(s) to be executed. In this guide we will demonstrate, passing function argument(s) value as mandatory. When the value is not given, function will prompt for parameter value.

Applies To






  • Tested on Windows 10, Windows 2008 R2 and Windows 2012.

  • Pre-Requisites






  • Launch PowerShell Command Console or PowerShell ISE.
  • To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or “Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”. Each Policy type and its purpose is shown in the below table.


  • Policy Type
    Purpose
    Restricted No scripts can be run. Windows PowerShell can be used only in interactive mode.
    AllSigned Only scripts signed by a trusted publisher can be run.
    RemoteSigned Downloaded scripts must be signed by a trusted publisher before they can be run.
    Unrestricted No restrictions; all Windows PowerShell scripts can be run.

    PowerShell Script – Function

    This PowerShell script call function without any function arguments / parameters.

    Code Snippet


    #
    # Simple Function with one Mandatory Argument Value
    #
    function MandatoryParameter
    {
        param(
            [Parameter(Mandatory=$True, Position=1)]
            [ValidateNotNullOrEmpty()]
            [string]$Parameter_Position_One
        )    
        Clear-Host
        Write-Host "`nParameter Value that was passed : $Parameter_Position_One`n" 
        [console]::beep(500,300)
    }
    

    Call / Invoke Function - Attribute Name

    To invoke / call the function, call the function from the PowerShell CLI or PowerShell ISE.

    MandatoryParameter 007



    PowerShell Output #1

    When the function is called / executed with parameter value being passed; below output will be displayed.


    Invoke Function – Without Passing Argument Value

    When the parameter/argument value is not passed; script will ask for input of argument value, as shown below;


    Invoke Function – Passing Argument Value Space

    When you intend to set the argument value with multiple words, enclose value with double quotes after invoking the function.

    PowerShell Output #2


    Invoke Function – Passing Argument Value

    When you intend to run the script is run with single quote;

    MandatoryParameter 'Function Parameter Passing Mandatory Argument Value'

    PowerShell Output #3


    Invoke Function – Passing Argument Value

    When you intend to run the script along with the against each parameter name its value;

    MandatoryParameter -Parameter_Position_One Parameter


    PowerShell Output #4


    Slideshare Information

    A step by step guide is uploaded to slideshare.



    No comments:

    Post a Comment