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 and an optional argument. When the value is not given for the mandatory, function will prompt for parameter value.Applies To
Pre-Requisites
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 with function’s mandatory argument / parameter value, when the argument value is passed; Passed value will be displayed else an exception will be thrown.Code Snippet
In this function, one “Parameter” is set to false and “Parameter” is set to true; for argument position 1 is optional and position 2 argument is mandatory.# # Simple Function With One Argument Mandatory Value and Second Argument Optional # function MandatoryParameter_And_OptionalParameter { param( [Parameter(Mandatory=$False, Position=1)] [string]$Parameter_Position_One, [Parameter(Mandatory=$True, Position=2)] [ValidateNotNull()] [string]$Parameter_Position_Two ) Clear-Host Write-Host "`n1st Parameter Value that was passed : $Parameter_Position_One`n" Write-Host "`n2nd Parameter Value that was passed : $Parameter_Position_Two`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. Invoke the function and pass value for the specific attribute.MandatoryParameter_And_OptionalParameter -Parameter_Position_Two Value_Passed
PowerShell Output #1
After execution of the function and mandatory argument value is passed; argument value is displayed as below;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;MandatoryParameter_And_OptionalParameter
No comments:
Post a Comment