EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Function Parameters

PowerShell Function Parameters

PowerShell Function Parameters

Introduction to PowerShell Function Parameters

PowerShell function parameters make function-rich by using attributes and arguments to restrict users to enter certain values. It adds a few checks and validations to avoid writing long codes for them, and they are easy to use. Once the function parameters are declared, arguments can be passed with the command line as well. Function parameters include named parameters, positional parameters, switch parameters, and dynamic parameters. Function parameters also help to convert simple function to advanced function.

Syntax of PowerShell Function Parameters

Parameters inside the functions are generally described inside the Param() block.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (85,992 ratings)

1. Named Parameter syntax with Single parameter.

function TestFunction{
param (
[Parameter()] [TypeName] $ParameterName
)
<Statement list>
}

In the above example, we can add multiple parameter values. There are different named parameter attributes like Mandatory, ValueFromPipeline, Position, ParameterSetName, etc. Typename is the datatype for the ParameterName like String, Integer, Character.

2. Named parameter syntax with Advanced function.

When we add the Cmdletbinding attribute, it converts a function into an advanced function. When the advanced function is created, the function uses other common parameters.

function TestFunction{
[CmdletBinding()] param (
[Parameter()] [TypeName] $ParameterName
)
<Statement list>
}

3. Parameters with attributes.

a. The parameter with a single argument.

function testparam{
param(
[Parameter(Argument=Value)] [ParameterType] $ParameterName)
}

b. The parameter with multiple arguments.

function testparam{
param(
[Parameter(Argument1=Value1,
Argument2=Value2)] [ParameterType] $ParameterName)
}

4. Parameter sets syntax.

function testparam{
Param(
[Parameter(AttributeValue1)] [ParameterType] [$ParameterName],
[Parameter(AttributeValue2)] [ParameterType] [$ParameterName] )
}

How Does Function Parameter work in PowerShell?

When we use the function parameters, and when PowerShell calls the function, it first checks the parameters declared in the function, like if the parameter is declared mandatory or specified the value from the pipeline or any other parameter specified.

You can also pass those parameters using the command line.

Example:

Code:

function Testfunct{
param(
[Parameter (Mandatory = $false)] [String]$Name
)
Write-Output "Name : $name"
}

You can pass the parameter as shown below.

Code:

Testfunct -Name "PowerShell"

You can also use the help for the function to the available parameters.

Output:

PowerShell Function Parameters 1

Examples of PowerShell Function Parameters

Given below are the examples of PowerShell Function Parameters:

Example #1

Simple function without parameter block.

In the below example, only the Param block is defined but not the Parameter block. We have simply declared the Name variable with String datatype.

Code:

Function PrintName{
param(
[String]$Name
)
Write-Output "Hello : $name !!! "
}
PrintName -Name PowerShell

Output:

PowerShell Function Parameters 2

Example #2

Function with mandatory parameter.

When you specify a mandatory parameter with $true value, you must pass the variable value while calling the function; otherwise, an error is generated.

The first example is equivalent to the mandatory parameter as false.

Code:

Function PrintName{
Param(
[Parameter(Mandatory=$false)] [String]$Name
)
Write-Output "Hello : $name !!! "
}
PrintName

If you call a function directly without specifying any values, then it will not give any error.

Output:

PowerShell Function Parameters 3

If you specify the mandatory parameter as true and call the function without passing any values, then it will ask for the value, and if you don’t specify that time, then It will generate a function error.

PowerShell Function Parameters 4

Providing value.

PowerShell Function Parameters 5

Without providing a mandatory value.

PowerShell Function Parameters 6

The above output generates the parameter binding exception.

Example #3

Function with positional parameter.

When we specify a function with a positional parameter, the keyword (Position), you don’t need to specify the parameter’s name. It is not necessary and mandatory with positional parameters.

Code:

Function Get-ServersInfo{
Param(
[Parameter(Mandatory=$true,Position=0)] [String[]]$ComputerName
)
Write-Output "Computers :"
$ComputerName
}
Get-ServersInfo Computer1,Computer2

Output:

Positional Parameter

In the above example, function Get-ServersInfo uses the default positional parameter Position=0, so we have directly passed computer names. If we have multiple positional parameters, then we will increment position with each parameter name.

Code:

Function Get-ServersInfo{
Param(
[Parameter(Mandatory=$true,Position=1)] [Int]$port,
[Parameter(Mandatory=$true,Position=0)] [String[]]$ComputerName
)
Write-Output "Computers :"
$ComputerName
}
Get-ServersInfo Computer1,Computer2 8080

Output:

PowerShell Function Parameters 8

In the above example, even if we declared port variable first but its positional value is 1, and the ComputerName variable position value is 0, so it is taking first the computer names.

Example #4

Function parameter with ValueFromPipeline Attribute.

When the ValueFromPipeline value is set to true, we can pass the variables using the Pipeline.

Code:

Function Get-ProcessInfo{
Param(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true)] [String[]]$Process
)
Get-Process -Process $Process
}
“Notepad” | Get-ProcessInfo

Output:

ValueFromPipeline Attribute

When we pass the multiple processes using Pipeline, it might not work, but the same will work by directly passing value.

PowerShell Function Parameters 10

Passing values using the pipeline.

Passing values using the pipeline

In that case, we can use the Begin, Process, and End blocks.

Code:

Function Get-ProcessInfo{
Param(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true)] [String[]]$Process
)
Begin{}
Process{Get-Process $Process}
end{}
}
“Notepad”,”Winword” | Get-ProcessInfo

Output:

PowerShell Function Parameters 12

Example #5

Function parameter with switch attribute.

Like the Switch function, we can use the switch parameter inside the function. In the below example, if we set the reboot switch value to true the true block will be executed; otherwise, the false block will be executed.

Code:

Function Check-Switch{
param(
[Parameter(Mandatory=$false,Position=0)] [Switch]$Reboot
)
if($Reboot){"Server Reboot requested"}
else{"Server will not reboot"}
}
Check-Switch $true
Check-Switch $false

Output:

Switch attribute

Example #6

Function parameter with a help message.

When you need to show a description of the parameter or need to put any help command related to that parameter, you can use the HelpMessage functionality. To show the message, you need to use, Get-Help command.

Code:

Function Check-HelpMsg{
param(
[Parameter(Mandatory=$true,HelpMessage="Enter the Name of the processes separated by comma")] [String[]]$Process
)
Begin{}
Process{Get-Process $Process}
End{}
}
help Check-HelpMsg -Full

Output:

Help Message

Example #7

Function parameter with validation set attributes.

Instead of writing the long validation inside the script, we can provide validation directly inside the Parameter block with validation sets.

Code:

Function Validate{
param(
[Parameter(Mandatory=$true)] [ValidateSet("Cat","Dog","Cow","Tiger")] [String[]]$Animals,
[Parameter(Mandatory=$true)] [ValidateRange(10,20)] [Int]$Age
)
Write-Output "Animals:"
$Animals
Write-Output "Age: $Age"
}
validate -Animals
validate -Animals Dog,Cow -Age 15

Output:

When you type the name of the parameter defined in the validation set, it pops up values. This is applicable in ISE but may not appear in the different consoles. In that case, we can use.

PowerShell Function Parameters 15JPG

Values within the validation range.

Values within the validation rang

Values outside the validation range throw exception.

Values outside the validation range throw exception

Conclusion

PowerShell function parameters are very useful, as we have seen in the above example. It reduces the code complexity by specifying them at the beginning of the function, and we don’t need to write the extra code to validate the data. We can use the exception handling mechanism to handle the exceptions.

Recommended Articles

This is a guide to PowerShell Function Parameters. Here we discuss the introduction, how does function parameter work in PowerShell? and examples. You may also have a look at the following articles to learn more –

  1. PowerShell Execution Policy
  2. PowerShell Sleep
  3. PowerShell SubString
  4. PowerShell Start-Process
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Secondary Sidebar
PowerShell Tutorial
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more