EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PowerShell Functions

By Chirag NagarekarChirag Nagarekar

Home » Data Science » Data Science Tutorials » PowerShell Tutorial » PowerShell Functions

PowerShell Functions

Introduction to PowerShell Functions

PowerShell function is used for the code reusability. When you write a big program, many times there are chances that you have to use the codes multiple times, so instead of writing it again and again, we can create a function that has all codes inside and call the function whenever necessary. PowerShell has two types of functions. Normal function and Advanced function.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])] {
param([type]$parameter1 [,[type]$parameter2])
dynamicparam {<statement list>}
begin {<statement list>}
process {<statement list>}
end {<statement list>}
}

Syntax for calling function:

functionname Argument1 Argument2

Parameters of PowerShell Functions

1. Scope: Scope of the function, used to prevent other objects, variables, functions, alises etc., from being inadvertently changed by scripts within the system.

2. Name: Name of the Function.

3. Parameters: When you pass the argument to the function, these parameter captures the arguments and pass them inside the function. This parameter has the same datatype as the argument.

4. Param: Param is useful for declaring the variables inside the function. It is also used with the advanced function.

5. Dynamicparam: Dynamic parameters are used for the advanced functions. Since only included whenever desired.

How do Functions Work in PowerShell?

The function contains the codes and can call another function(s). To create a function, as mentioned in the above syntax, you first need to create the function and then call it within a program, or you can call the function outside a program once it is executed. For example:

Popular Course in this category
Sale
PowerShell Training (2 Courses, 1 Project)2 Online Courses | 1 Hands-on Project | 4+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,985 ratings)
Course Price

View Course

Related Courses
Shell Scripting Training (4 Courses, 1 Project)All in One Data Science Bundle (360+ Courses, 50+ projects)Data Visualization Training (15 Courses, 5+ Projects)

Code:

function Printvalue($value1){
Write-Output "Value is : $value1"
}
Printvalue "Hello World"

Output:

PowerShell Functions Example

Explanation: Here, we have first declared a function called PrintValue, which prints the data, and we will call the function with the function name and by passing the argument “Hello World” and $Value1 captures it and pass it to the function.

You can also just write the function and execute it by the function name from the PowerShell console. For Example: Take the same above function but don’t print the value inside the function, but we will print it from the console after program execution.

Code:

function Printvalue($value1){
Write-Output "Value is : $value1"
}

Output:

PowerShell Functions Example

Examples to Implement PowerShell Functions?

Below are the examples of PowerShell Functions:

Example #1

PowerShell “function” with no argument. Below is an example of a function without any arguments and parameters.

Code:

function callfunct{
Write-Output "Function called"
}
callfunct

Output:

PowerShell Functions Example 1

Example #2

PowerShell “function” with one argument. An example of passing one argument to function and function captures it with one parameter.

Code:

function callfunct($param1){
Write-Output "Value : $param1"
}
callfunct 20

Output:

One Argument Example 2

Example #3

PowerShell “functions” with multiple arguments. You can pass multiple arguments to a function.

Code:

function addition($value1, $value2){
$value = $value1 + $value2
Write-Output "Total : $Value"
}
addition 20 30

Output:

Multiple Arguments Example 3

Similarly, you can pass more arguments to the function. For example,

Functionname Argument1 Argument2 Argument3…… ArgumentN

Example #4

PowerShell “function” with the “Return” value. You can use the return parameter to return the output from the function to the call.

Code:

function addition($value1, $value2){
return $value1 + $value2
}
$output = addition 20 30
Write-Output "Sum : $output"

Output:

PowerShell Functions Example 4

Here, the function returns the value, and it is captured by the $output variable.

Example #5

Passing an array to the function. We can also pass the entire array to the function.

Code:

$a = @(10,20,30,40,50)
function arrayfunct($values){
Write-Output $values
}
arrayfunct $a

Output:

PowerShell Functions Example 5

Example #6

Return array from the function. An array can be returned too from the function. See the example below.

Code:

function callarray{
$a = @(10,20,30,40,50)
return $a
}
$arr = callarray
Write-Output $arr

Output:

Array Example 6

In the example above, the function returns the array values and which are captured by variable $arr.

Example #7

Nested functions. You can call the function inside the function as well. In the below example, we will pass two values to a function, which will be summed up and then passed to another function to get double its value.

Code:

function square($a){
return $a * $a
}
function addition($value1,$value2){
$sum = $value1 + $value2
$sqr = square $sum
return $sqr
}
$out = addition 5 6
Write-Output "Square : $out"

Here, two values, 5 and 6, are passed to function addition, which will be summed up and then the output will be passed to the square function (value: 11) to get the square of it and finally, the output will be returned is 121.

Output:

PowerShell Functions Example 7

Example #8

Parameter declaration inside the PowerShell Function. You can declare parameters inside the function. So at the beginning of the function, parameters will be initialized. It is similar to assigning the values to the variables but looks more structured when you use the advanced function.

Code:

function parametertest{
param(
$name = "Donald",
$Citizen = "US"
)
Write-Output "Name : $name"
Write-Output "Citizen : $citizen"
}
parametertest

Output:

Parameter Declaration Example 8

Conclusion

There is no doubt that function provides the great reusability of the code with advanced functionality. The function is also an important part of any programming language because it creates a program in a more structural and easy to understand the flow of the program. Most people use the advanced function while writing the huge lines of codes, so it also helps in capturing the error output and for the debug purpose.

Recommended Articles

This is a guide to PowerShell Functions. Here we discuss the Introduction to the PowerShell Functions and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –

  1. Switch Case Works in PowerShell?
  2. PowerShell Tools
  3. PowerShell Scheduled Task
  4. PowerShell Convert to String
  5. PowerShell Send Mail

PowerShell Training (2 Courses)

2 Online Courses

1 Hands-on Project

4+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PowerShell Tutorial
  • 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
  • Basics
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • 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 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
  • 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

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

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
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 Login

Forgot Password?

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.

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.

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

Special Offer - PowerShell Training (2 Courses) Learn More