{"id":139,"date":"2023-12-30T16:41:32","date_gmt":"2023-12-30T22:41:32","guid":{"rendered":"https:\/\/techlensfocus.com\/?p=139"},"modified":"2024-03-05T22:09:22","modified_gmt":"2024-03-06T04:09:22","slug":"getting-started-with-powershell-function-parameters-part-1","status":"publish","type":"post","link":"https:\/\/techlensfocus.com\/index.php\/2023\/12\/30\/getting-started-with-powershell-function-parameters-part-1\/","title":{"rendered":"Getting Started with PowerShell Function Parameters Part 1"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"wp-block-ideabox-toc ib-block-toc\" data-anchors='h2,h3,h4,h5,h6' data-collapsable='true' ><div class=\"ib-toc-container ib-toc-list-style-numbers ib-toc-hierarchical ib-toc-expanded\"><div class=\"ib-toc-header\"><div class=\"ib-toc-header-title\">Table of Contents<\/div><div class=\"ib-toc-header-right\"><span class=\"ib-toc-icon-collapse\"><span class=\"dashicon dashicons dashicons-minus\"><\/span><\/span><span class=\"ib-toc-icon-expand\"><span class=\"dashicon dashicons dashicons-plus\"><\/span><\/span><\/div><\/div><div class=\"ib-toc-separator\" style=\"height:2px\"><\/div><div class=\"ib-toc-body\"><ol class=\"ib-toc-anchors\"><\/ol><\/div><\/div><\/div>\n\n\n\n<p><\/p>\n\n\n\n<p>PowerShell functions are the building blocks of automation, and understanding their parameters is key to crafting efficient and adaptable scripts. Let&#8217;s explore the power and versatility that parameters bring to PowerShell functions.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding PowerShell Function Parameters<\/h2>\n\n\n\n<p>PowerShell function parameters are variables that you define within a function to accept input values from the calling code. Parameters allow you to create flexible and reusable functions by specifying placeholders for values that can be passed when the function is called. <\/p>\n\n\n\n<p>PowerShell function parameters are crucial for customizing and reusing functions across projects, allowing dynamic execution and automation. They enforce consistency, prevent errors, and streamline workflows in production environments. Parameters adapt scripts to varying needs, ensuring adaptability and easy testing for specific functionalities.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Making PowerShell Function with Parameters and Examples<\/h2>\n\n\n\n<p>Now let&#8217;s create a PowerShell Function with Parameters step by step:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1<\/h4>\n\n\n\n<p><strong>Step 1:<\/strong> Creating function<\/p>\n\n\n\n<p>Use the <em><strong><code>function<\/code> <\/strong><\/em>keyword followed by the name you want to assign to your function. Then, use a pair of curly braces <code><strong>{}<\/strong><\/code> to encapsulate the code<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Test1\n{\n    \n}\n<\/pre>\n\n\n\n<p><strong>Step 2: <\/strong>Add Parameters<\/p>\n\n\n\n<p>Use the <strong><em><code>param()<\/code> <\/em><\/strong>block inside the function. Define each parameter using its name and data type. You can also set default values or define optional parameters. Below the function take two parameters (<strong>$param1<\/strong> and <strong>$param2<\/strong>)<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Test1 \n{\n    param(\n        [string]$param1,\n        [int]$param2\n    )\n\n}\n<\/pre>\n\n\n\n<p><strong>Step 3:<\/strong> Utilize the Parameters<\/p>\n\n\n\n<p>For example,<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Test1 \n{\n    param(\n        [string]$param1,\n        [int]$param2\n    )\n\n    Write-Host \"Parameter 1: $param1\"\n    Write-Host \"Parameter 2: $param2\"\n}\n\n# Test the function \nTest1 -param1 \"This is a test\" -param2 12<\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"58\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2024\/01\/Screenshot13-1-1024x58.png\" alt=\"\" class=\"wp-image-481\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2024\/01\/Screenshot13-1-1024x58.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2024\/01\/Screenshot13-1-300x17.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2024\/01\/Screenshot13-1-768x44.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2024\/01\/Screenshot13-1.png 1233w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>PowerShell also supports various parameter types beyond basic data types like <strong>[string]<\/strong> and <strong>[int] <\/strong>such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Boolean : <strong>[bool]<\/strong><\/li>\n\n\n\n<li>Array: <strong>[array]<\/strong><\/li>\n\n\n\n<li>Hash Table: <strong>[hashtable]<\/strong><\/li>\n\n\n\n<li>DateTime: <strong>[datetime]<\/strong><\/li>\n\n\n\n<li>Custom Object: <strong>[MyCustomObject]<\/strong><\/li>\n\n\n\n<li>Switch: <strong>[switch]<\/strong>, acting as a switch (true\/false without a value) <\/li>\n\n\n\n<li>File or Path: <strong>[System.IO.FileInfo]<\/strong> this type of parameter accept file paths or specific files<\/li>\n\n\n\n<li>ValidatePattern: <strong>[ValidatePattern()]<\/strong>, Validates input using a regular expression pattern<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Example 2<\/h4>\n\n\n\n<p>Here&#8217;s an example using a <strong>[bool]<\/strong> (Boolean) parameter type<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Check-Status \n{\n    param(\n        [bool]$IsActive\n    )\n    if ($IsActive) \n    {\n        Write-Host \"The status is active.\"\n    } \n    else \n    {\n        Write-Host \"The status is inactive.\"\n    }\n}\n\n# Calling the function with a boolean argument\nCheck-Status -IsActive $true\n<\/pre>\n\n\n\n<p>Output: <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"81\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot2-1024x81.png\" alt=\"\" class=\"wp-image-160\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot2-1024x81.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot2-300x24.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot2-768x61.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot2.png 1248w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>In this example, the <strong>Check-Status<\/strong> function takes a <strong>[bool]<\/strong> parameter named <strong>$IsActive<\/strong>. Inside the function, it checks the value of the <strong>$IsActive<\/strong> parameter. If it&#8217;s <code>true<\/code>, it outputs that the status is active; otherwise, it states that the status is inactive. In this case, we pass the argument <strong>-IsActive $true<\/strong>, indicating that the status is active. You can change <strong>$true<\/strong> to <strong>$false<\/strong> when calling the function to observe the &#8220;inactive&#8221; status output.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 3: <\/h4>\n\n\n\n<p>Here&#8217;s an example using a<strong> [switch]<\/strong> parameter type<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Toggle-Status \n{\n    param(\n        [switch]$Enable\n    )\n\n    if ($Enable) \n    {\n        \"Status is enabled.\"\n    } \n    else \n    {\n        \"Status is disabled.\"\n    }\n}\n\n# Calling the function without enabling the status (switch not specified)\nToggle-Status\n\n# Calling the function and explicitly enabling the status using the switch parameter\nToggle-Status -Enable<\/pre>\n\n\n\n<p>The <strong>Toggle-Status<\/strong> function has a single parameter named <strong>$Enable<\/strong> of type <strong>[switch]<\/strong>. When the function is called without specifying <strong>-Enable<\/strong>, it defaults to <strong>$false<\/strong>. When you call the function with <strong>-Enable<\/strong>, it sets the switch parameter to <code>$true<\/code>. Try running the code the see the outputs.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the [Parameter()] Attributes<\/h2>\n\n\n\n<p> If you want to add additional attributes or properties to your parameters, you can use <strong>[Parameter()]<\/strong> along with various options to customize their behavior. <strong>[Parameter()]<\/strong> is an attribute used to define parameters within a function such as its position, mandatory status, default values, etc. For instance, you can use it to define parameter properties like this:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code><strong>[Parameter(Mandatory = $true)]<\/strong><\/code> makes the parameter mandatory<\/li>\n\n\n\n<li><strong><code>[Parameter(Position = 0)]<\/code> <\/strong>specifies the position of the parameter<\/li>\n\n\n\n<li><code><strong>[Parameter(ValueFromPipeline = $true)]<\/strong><\/code> allows the parameter to accept input from the pipeline, among others<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s look at some examples:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1: Function with Mandatory parameter<\/h4>\n\n\n\n<p>In this example, we will using Function with mandatory parameter. When you set a parameter as mandatory by assigning it a value of <code>$true<\/code>, you must provide a value for that variable when calling the function.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Print-Info \n{\n    param(\n        [Parameter(Mandatory=$true)]\n        [int]$Number\n    )\n\n    \"The provided number is: $Number\"\n}\n\n# Calling the Function\nPrint-Info -Number 12\n\n# Note that Calling the function without providing the mandatory parameter\n# will generate an error because the mandatory parameter is missing<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"70\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot3-1024x70.png\" alt=\"\" class=\"wp-image-179\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot3-1024x70.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot3-300x21.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot3-768x53.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot3.png 1239w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\">Example 2: Function with Positional parameter<\/h4>\n\n\n\n<p>A function with positional parameters in PowerShell is a function where the parameters can be passed based on their positions rather than explicitly using their names. Positional parameters can be useful when you have functions with multiple parameters, and their order of usage is consistent. See example below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Greet-User \n{\n    param(\n        [Parameter(Position=0)]\n        [string]$FirstName,\n\n        [Parameter(Position=1)]\n        [string]$LastName\n    )\n\n    \"Hello, $FirstName $LastName! Welcome to PowerShell.\"\n}\n\n# Calling the function using positional parameters\nGreet-User \"John\" \"Doe\"<\/pre>\n\n\n\n<p>Output: <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"75\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot4-1024x75.png\" alt=\"\" class=\"wp-image-182\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot4-1024x75.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot4-300x22.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot4-768x56.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot4.png 1243w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>This function <strong>Greet-User<\/strong>, the parameters <strong>$FirstName<\/strong> and <strong>$LastName<\/strong> are set with specific positions using the <strong>[Parameter(Position=X)] <\/strong>attribute. This means when you call the function, you can pass the arguments in the order of their positions without explicitly mentioning the parameter names. <strong>&#8220;John&#8221;<\/strong> will be assigned to <strong>$FirstName<\/strong> because it&#8217;s the first positional parameter, and <strong>&#8220;Doe&#8221;<\/strong> will be assigned to <strong>$LastName<\/strong> as it&#8217;s the second positional parameter.<\/p>\n\n\n\n<p>However, you should explicitly specifying the parameter names while calling the function as it makes your script more readable and less error-prone, especially with functions that have numerous parameters or if the parameter order might be ambiguous.<\/p>\n\n\n\n<p>You can also use both the <strong>Mandatory<\/strong> and <strong>Position<\/strong> attributes together for a parameter in a function: <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Get-Info \n{\n    param(\n        [Parameter(Mandatory=$true, Position=0)]\n        [string]$Name,\n\n        [Parameter(Position=1)]\n        [int]$Age\n    )\n\n    \"Name: $Name\"\n    if ($Age) \n    {\n        \"Age: $Age\"\n    } \n    else \n    {\n        \"Age not provided.\"\n    }\n}\n\n# Calling the function using positional parameters\nGet-Info \"John\" 30<\/pre>\n\n\n\n<p>Output: <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"67\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot5-1024x67.png\" alt=\"\" class=\"wp-image-184\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot5-1024x67.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot5-300x20.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot5-768x50.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot5.png 1239w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>In this <code>Get-Info<\/code> function:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>$Name<\/strong> is set as a mandatory parameter and is also the first positional parameter.<\/li>\n\n\n\n<li><strong>$Age<\/strong> is set as a non-mandatory parameter and is the second positional parameter.<\/li>\n<\/ul>\n\n\n\n<p>In the output, <strong>&#8220;John&#8221;<\/strong> is assigned to <strong>$Name<\/strong> (first positional parameter), and <strong>30 <\/strong>will be assigned to <strong>$Age <\/strong>(second positional parameter). The <code>Mandatory<\/code> attribute ensures that <strong>$Name<\/strong> must be provided when calling the function, while <strong>$Age<\/strong> remains optional since it doesn&#8217;t have the Mandatory attribute.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 3 Function with ParameterSetName<\/h4>\n\n\n\n<p>The <strong>ParameterSetName<\/strong> feature allows you to define different sets of parameters within a function. Each set, identified by a unique ParameterSetName can have its own parameters, providing flexibility in how the function is called and what parameters are required or optional based on a specific scenario. This approach allows you to create more versatile functions that adapt to different scenarios by defining different sets of parameters, each applicable under specific conditions or use cases.<\/p>\n\n\n\n<p>Below is an example simulates a function to manage network settings based on different parameter sets:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Set-NetworkSettings \n{\n    param (\n        [Parameter(ParameterSetName='StaticIP', Mandatory=$true)]\n        [string]$IPAddress,\n\n        [Parameter(ParameterSetName='StaticIP', Mandatory=$true)]\n        [string]$SubnetMask,\n\n        \n        [Parameter(ParameterSetName='DHCP', Mandatory=$true)]\n        [switch]$UseDHCP\n    )\n    \n    if ($PSCmdlet.ParameterSetName -eq 'StaticIP') \n    {\n        \"Setting static IP: $IPAddress, Subnet Mask: $SubnetMask\"\n        # Apply static IP settings\n    }\n\n    if ($PSCmdlet.ParameterSetName -eq 'DHCP') \n    {\n        \"Using DHCP for IP configuration.\"\n        # Configure network to use DHCP\n    }\n}\n\n# Setting network settings with a static IP address\nSet-NetworkSettings -IPAddress \"192.168.1.100\" -SubnetMask \"255.255.255.0\"\n\n# Configuring the network to use DHCP\nSet-NetworkSettings -UseDHCP<\/pre>\n\n\n\n<p>Output 1: Setting network settings with a static IP address<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"60\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot8-1024x60.png\" alt=\"\" class=\"wp-image-201\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot8-1024x60.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot8-300x18.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot8-768x45.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot8.png 1234w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Output 2: If we configuring the network to use DHCP<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"64\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot9-1024x64.png\" alt=\"\" class=\"wp-image-202\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot9-1024x64.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot9-300x19.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot9-768x48.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot9.png 1243w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>In the example above, the <strong>Set-NetworkSettings<\/strong> function has two parameter sets: &#8216;StaticIP&#8217; and &#8216;DHCP&#8217; <\/p>\n\n\n\n<p>&#8216;StaticIP&#8217; expects parameters <strong>$IPAddress <\/strong>and <strong>$SubnetMask<\/strong> for setting a static IP address<\/p>\n\n\n\n<p>&#8216;DHCP&#8217; includes a [switch] parameter<strong> $UseDHCP<\/strong> to specify using DHCP for network configuration<\/p>\n\n\n\n<p><strong>$PSCmdlet <\/strong>is a PowerShell automatic variable that refers to the cmdlet or script from within which it is accessed. It provides access to properties and methods related to the current cmdlet execution context. In the context of a function with multiple parameter sets, <strong>$PSCmdlet.ParameterSetName<\/strong> is used to determine which parameter set was used when the function was called.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the [ValidateSet()] attributes<\/h2>\n\n\n\n<p>The <strong>[ValidateSet()]<\/strong> attribute in PowerShell is used to limit the input of a parameter to a predefined set of valid values. It ensures that only specified values are accepted for that particular parameter. This can be useful for user inputs or configuration settings.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1<\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Set-Environment \n{\n    param(\n        [ValidateSet(\"Development\", \"Testing\", \"Production\")]\n        [string]$Environment\n    )\n\n    Write-Host \"Selected environment: $Environment\"\n    # Additional operations based on the selected environment\n}\n\n# Valid call using one of the specified values\nSet-Environment -Environment \"Development\"\n\n# Invalid call using a value not included in the ValidateSet\n# This will give error\nSet-Environment -Environment \"Staging\"<\/pre>\n\n\n\n<p>Output 1: <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"56\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot6-1024x56.png\" alt=\"\" class=\"wp-image-193\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot6-1024x56.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot6-300x16.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot6-768x42.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot6.png 1225w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Output 2: when you put a value that is not included in the ValidateSet<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"154\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot7-1024x154.png\" alt=\"\" class=\"wp-image-194\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot7-1024x154.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot7-300x45.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot7-768x116.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot7.png 1216w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>The<strong> Set-Environment <\/strong>function has a parameter named <strong>$Environment<\/strong>. <strong>[ValidateSet(&#8220;Development&#8221;, &#8220;Testing&#8221;, &#8220;Production&#8221;)]<\/strong> restricts the valid values for <strong>$Environment<\/strong> to only &#8220;Development&#8221;, &#8220;Testing&#8221;, or &#8220;Production&#8221;. If any other value is provided, PowerShell will throw an error indicating that the input is not valid. <\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using Begin, Process, End <\/h2>\n\n\n\n<p><strong>Begin<\/strong>, <strong>Process <\/strong>, <strong>End <\/strong>are script blocks that can be utilized in advanced functions, especially when dealing with cmdlets and scripts that handle pipeline input. These blocks are particularly useful when dealing with commands that accept input from the pipeline (<strong>ValueFromPipeline=$true<\/strong>). They provide a structured way to handle iterative processing of objects passed through the pipeline.<\/p>\n\n\n\n<p>If your PowerShell function or script doesn&#8217;t rely on or accept pipeline input, there might not be a significant need to use the <strong>Begin<\/strong>, <strong>Process <\/strong>and <strong>End <\/strong>block.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1: <\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Count-Characters \n{\n    param (\n        [Parameter(ValueFromPipeline=$true)]\n        [string]$Text\n    )\n\n    begin \n    {\n        Write-Host \"Starting character count.\"\n    }\n    process \n    {\n        $charCount = $Text.Length\n        Write-Host \"Text: $Text - Character count: $charCount\"\n    }\n    end \n    {\n        Write-Host \"Ending character count.\"\n    }\n}\n\n# Use the Function\n\"Hello\", \"Goodbye\", \"PowerShell\" | Count-Characters\n<\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"97\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot10-1024x97.png\" alt=\"\" class=\"wp-image-219\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot10-1024x97.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot10-300x28.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot10-768x73.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot10.png 1239w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>This function <strong>Count-Characters<\/strong>, calculates the character count of text passed through the pipeline<\/p>\n\n\n\n<p>In Powershell there are two kind of types of pipeline input, known as <strong>ByValue <\/strong>and <strong>ByPropertyName <\/strong><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">ByValue (Entire Object)<\/h4>\n\n\n\n<p>This type of pipeline input accepts the entire object passed through the pipeline. Here&#8217;s an example<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Multiply-Number \n{\n    param (\n        [Parameter(ValueFromPipeline=$true)]\n        [int]$Number,\n        [int]$Factor\n    )\n\n    process \n    {\n        $result = $Number * $Factor\n        Write-Output $result\n    }\n}\n\n# Use the Function \n1, 2, 3, 4 | Multiply-Number -Factor 10<\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"81\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-1-1024x81.png\" alt=\"\" class=\"wp-image-228\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-1-1024x81.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-1-300x24.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-1-768x61.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-1.png 1246w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>In this example, the numbers 1,2,3,4 are passed through the pipeline as individual objects. The <strong>Multiply-Number <\/strong>function receives each of these numbers as a whole object due to<strong> ValueFromPipeline=$true<\/strong><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">ByPropertyName (Single Object Property)<\/h4>\n\n\n\n<p>This type of pipeline input operates on a single property of an object passed through the pipeline. Here&#8217;s an example<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Capitalize-Property \n{\n    param (\n        [Parameter(ValueFromPipelineByPropertyName=$true)]\n        [string]$Name\n    )\n    \n    process \n    {\n        $result = $Name.ToUpper()\n        Write-Output $result\n    }\n}\n\n# Assume we have a custom object with a property called Name:\n$person = [PSCustomObject]@{\n    Name = \"john\"\n}\n\n# Pass this object through the pipeline and modify its Name property\n$person | Capitalize-Property<\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"40\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-2-1024x40.png\" alt=\"\" class=\"wp-image-232\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-2-1024x40.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-2-300x12.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-2-768x30.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-2.png 1249w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>This example takes the property <code>Name<\/code> of the object <strong>$person<\/strong> and capitalizes it using the<strong> Capitalize-Property <\/strong>function. <strong>ValueFromPipelineByPropertyName=$true<\/strong> parameter attribute enables this behavior, allowing the function to work on the specified property of the incoming object.<\/p>\n\n\n\n<p>So choosing between <strong>ByValue<\/strong> and <strong>ByPropertyNam<\/strong>e pipeline input largely depends on the context of your script or function and the nature of the data you&#8217;re dealing with<\/p>\n\n\n\n<p>If your function needs to process the entirety of each object passing through the pipeline, use <strong>ValueFromPipeline=$true<\/strong>. For instance, if you&#8217;re performing actions on complete objects like files, services, or custom objects where all properties matter.<\/p>\n\n\n\n<p>If your function or script operates on specific properties of objects rather than the entire object, <strong>ValueFromPipelineByPropertyName=$true <\/strong>is beneficial. For example, if you want to modify specific attributes like filenames, usernames, specific properties of objects, etc.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the [CmdletBinding()] attributes<\/h2>\n\n\n\n<p><strong>[CmdletBinding()]<\/strong> is an attribute used in PowerShell functions to enable advanced features associated with cmdlets. Here are some scenarios when you should consider using <strong>[CmdletBinding()]<\/strong><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1<\/h4>\n\n\n\n<p><strong>Using Common Parameter:<\/strong> If you want your function to support common parameters like <strong>-Verbose<\/strong>, <strong>-Debug<\/strong>, <strong>-ErrorAction<\/strong>, <strong>-WarningAction<\/strong>, etc then <strong>[CmdletBiding()]<\/strong> is necessary<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Test-Function \n{\n    [CmdletBinding()]\n    param (\n        [Parameter()]\n        [int]$Number\n    )\n\n    Write-Verbose \"Verbose mode activated.\"\n    \n    try \n    {\n        $result = 10 \/ $Number\n        Write-Output \"Result: $result\"\n    } \n    catch \n    {\n        Write-Error \"Error occurred: $_\"\n    }\n}\n\n# Use the Function \nTest-Function -Number 0 -Verbose -ErrorAction Stop<\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"133\" src=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-3-1024x133.png\" alt=\"\" class=\"wp-image-247\" srcset=\"https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-3-1024x133.png 1024w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-3-300x39.png 300w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-3-768x100.png 768w, https:\/\/techlensfocus.com\/wp-content\/uploads\/2023\/12\/Screenshot11-3.png 1234w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>In this example, <strong>Write-Verbose<\/strong> is used to output verbose information if <strong>-Verbose<\/strong> is specified when calling the function. The <strong>try-catch<\/strong> block is used to handle errors. If an error occurs during the division, it&#8217;s caught and displayed using <strong>Write-Error<\/strong><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 2<\/h4>\n\n\n\n<p><strong>SupportsShouldProcess<\/strong>: [CmdletBinding()] allow you to confirm potentially destructive actions before execution, prove a safer user experience.<\/p>\n\n\n\n<p>Note that [CmdletBinding ]<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Remove-File \n{\n    [CmdletBinding(SupportsShouldProcess=$true)]\n    param (\n        [Parameter(Mandatory=$true)]\n        [string]$FilePath\n    )\n\n    if ($PSCmdlet.ShouldProcess(\"Delete file: $FilePath\", \"Confirm deletion\")) \n    {\n        Remove-Item -Path $FilePath -Force\n        Write-Output \"File $FilePath has been deleted.\"\n    } \n    else \n    {\n        Write-Output \"Deletion of file $FilePath was canceled.\"\n    }\n}\n\n# Use the Function \nRemove-File -FilePath \"C:\\Path\\To\\File.txt\" -WhatIf<\/pre>\n\n\n\n<p>In this example, <strong>[CmdletBinding(SupportsShouldProcess-$true)] <\/strong>enables the support for <strong>ShouldProcess()<\/strong>. The <strong>ShouldProcess() <\/strong>prompts the user for confirmation before deleting the file specified by $FilePath.<\/p>\n\n\n\n<p>In this case,<strong> -Whatif<\/strong> parameter allow you to see what would happen without actually performing the action. If you remove <strong>-Whatif <\/strong>it will prompt you for confirmation before deleting the file.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In conclusion, PowerShell function parameters promote modularity, flexibility, and clarity, enabling the creation of adaptable, reusable, and user-friendly functions that cater to diverse scenarios and enhance automation capabilities.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Automate tasks and customize scripts with powerful PowerShell function parameters. Validate inputs, enhance flexibility.<\/p>\n","protected":false},"author":1,"featured_media":258,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[6,15],"tags":[22,21,20],"class_list":["post-139","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-it","category-powershell","tag-function-parameters-in-powershell","tag-parameters","tag-powershell-function"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/posts\/139","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/comments?post=139"}],"version-history":[{"count":105,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/posts\/139\/revisions"}],"predecessor-version":[{"id":856,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/posts\/139\/revisions\/856"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/media\/258"}],"wp:attachment":[{"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/media?parent=139"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/categories?post=139"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techlensfocus.com\/index.php\/wp-json\/wp\/v2\/tags?post=139"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}