Functions are reusable blocks of code that perform a specific task in PowerShell. They help modularize your scripts by compartmentalizing logical segments. Once defined, a function can be invoked multiple times without having to rewrite the entire block of code.

This comprehensive guide will walk you through the fundamentals of calling a function within PowerShell.

What is a Function in PowerShell?

A function in PowerShell is defined using the function keyword followed by the function name and code block enclosed in curly braces {}.

Here is the basic syntax:

function Function-Name {
   # Function code goes here 
}

When this function is called later in the script, the code inside the function executes.

Functions accept input in the form of parameters and return output. The parameters allow passing dynamic data into the function.

For example:

function Get-Text($name) {
   return "Hello $name"  
}

Get-Text -name "John"

This function accepts the $name parameter and outputs a greeting with that name.

The key aspects of functions are:

  • Encapsulation: The function code is wrapped in a block that groups related statements. This avoids repitition.
  • Reusability: Functions can execute multiple times upon invocation.
  • Modularity: Complex scripts can be broken into smaller functions.
  • Abstraction: Functions hide complex implementation details from the user.

Next, let‘s see how to call or invoke these functions in PowerShell.

Calling a Function in PowerShell

To call a function in PowerShell, simply type out its name:

Function-Name

If the function accepts arguments, pass them along:

Function-Name -Arg1 Value1 -Arg2 Value2

When called, PowerShell executes all the code inside the function block.

It is important that the function is defined before calling it. PowerShell reads and interprets the code line by line. Any invocation before the actual function declaration will throw an error.

Now let‘s put these concepts into action with some examples.

Calling Functions in PowerShell ISE

PowerShell ISE is an integrated scripting environment for authoring and testing scripts. Let‘s define and invoke functions within the ISE console.

Step 1 – Define the Function

First, create a new PowerShell ISE file and define a function in it:

function Get-CurrentTime {
   Get-Date -DisplayHint Time 
}

This function fetches the current time when called.

Step 2 – Call the Function

Now, call this function directly in the console pane below:

Get-CurrentTime

Upon calling, it will execute the function code and display the output:

Calling a Function in PowerShell ISE

The Get-CurrentTime function was invoked successfully returning the current time.

Similarly, any other defined functions can also be called directly in the ISE console.

Calling Functions in the PowerShell Console

Functions can also reside and execute within the PowerShell console.

Follow these steps:

Step 1 – Define the function

Launch a PowerShell terminal and define the function:

function Show-Hello {
   Write-Output "Hello World!"
}

This prints a Hello World greeting.

Step 2 – Invoke the function

Call the function by its name:

Show-Hello

Here is the output:

Invoke a function in PowerShell console

The Show-Hello function was called properly displaying the message.

So PowerShell console can also leverage functions defined in it.

Calling Functions Within a Script

Thus far, we have defined and invoked functions interactively within the console.

But functions become extremely useful when executed from scripts.

Here is an example script with multiple functions:

# Validate input parameter

function Test-Number($number) {
   # Validation logic   
   if($number -gt 10) {
      return $true
   } 
   return $false
}

# Main logic function

function Start-Process() {

   $num = 15

   if(Test-Number $num) {
      Write-Output "Valid number"
   }
   else {
      Write-Output "Invalid number" 
   }

}

# Invoke main function
Start-Process

This script contains two functions:

  • Test-Number: Validates if the input number is greater than 10.
  • Start-Process: Executes the core logic calling Test-Number internally.

The key things to note are:

  • Functions defined first before calling them.
  • The Start-Process function invokes Test-Number by passing a variable.
  • Modularization using multiple functions to simplify logic.
  • Final call to Start-Process function to kick off execution.

When this script runs, the output is:

Valid number

This demonstrates functions executing successfully within a PowerShell script.

Calling Functions Recursively

A recursive function is one that calls itself within its own definition. This technique is useful to repeat the same processing logic iteratively.

Here is an example of a recursive function in PowerShell:

function Loop-Numbers($count) {

   Write-Output $count

   if($count -le 10) {
      $count += 1
      Loop-Numbers -count $count
   }

}

Loop-Numbers -count 1

This function:

  • Prints out the number passed to it.
  • Increments the number.
  • Calls itself recursively until the termination condition ($count greater than 10)

When invoked initially with count 1, the output will be:

1
2
3
4
5
6 
7
8
9
10

It iteratively calls itself 10 times printing numbers from 1 to 10.

This exhibits the recursive nature of functions calling themselves.

Calling Module Functions in PowerShell

PowerShell modules package a set of functions and cmdlets that can be imported and leveraged in your scripts.

Here is an example to use functions within an imported module:

Step 1 – Import Module

First, import the module using Import-Module, say SqlServer module:

Import-Module SqlServer

Step 2 – Invoke Module Function

Now directly call the required function present within that module:

New-SqlDatabase -Name MyDb -ServerInstance localhost

This will execute the New-SqlDatabase function defined as part of SqlServer module.

Similarly, you can invoke other module functions upon importing that PowerShell module.

Calling .NET Framework Functions

PowerShell also provides access to the entire .NET Framework API library encompassing a vast array of reusable functions.

To call a .NET method, use this syntax:

$Object = New-Object Namespace.Class

$Object.MethodName()  

Here is an example:

$dt = New-Object System.DateTime 

$dt.ToString("d")

This calls the DateTime class‘ ToString() method dynamically in PowerShell script.

Likewise, any .NET Framework assembly methods can be called directly by instantiating that class.

Summary

Functions empower code reuse, abstraction, and modularity in PowerShell. Defining small, focused functional units avoids duplication resulting in more maintainable and readable scripts.

We explored various techniques to call a function within PowerShell:

  • Call directly in PowerShell ISE after defining function
  • Invoke inside PowerShell console by typing function name
  • Call functions present in PowerShell scripts
  • Leverage recursive functions that self-invoke
  • Utilize module functions by importing that package
  • Invoke methods from .NET libraries dynamically

Functions have become integral units of automation. This article covers the fundamentals of calling them across various PowerShell executables. Use these actionable insights to get started with efficient coding!

Similar Posts