Saturday, January 18, 2025
HomeTechFunction return value in PowerShell

Function return value in PowerShell

In PowerShell, functions can return values in several ways. You can use the return keyword or simply output the value you want to return, as all output in PowerShell (unless explicitly suppressed) is considered part of the function’s return value.

Defining a Function with Return Value

Here’s the syntax to define and use a function with a return value:

function FunctionName {
    # Logic inside the function
    return <value>
}

Examples of Returning Values

1. Using return Keyword

The return keyword explicitly specifies the value to be returned by the function.

function Add-Numbers {
    param ($a, $b)
    return $a + $b
}

# Call the function
$result = Add-Numbers -a 5 -b 10
Write-Host "The result is: $result"

Output:

The result is: 15

2. Implicit Output

PowerShell functions automatically return all output unless explicitly suppressed (e.g., using Write-Output or piping to Out-Null).

function Multiply-Numbers {
    param ($a, $b)
    $a * $b  # No explicit return
}

# Call the function
$result = Multiply-Numbers -a 4 -b 3
Write-Host "The result is: $result"

Output:

The result is: 12

3. Using Write-Output

The Write-Output cmdlet is often used to make it explicit that a value is being sent to the output stream.

function Get-Message {
    param ($name)
    Write-Output "Hello, $name!"
}

# Call the function
$message = Get-Message -name "John"
Write-Host $message

Output:

Hello, John!

Multiple Return Values

PowerShell functions can return multiple values by outputting multiple objects.

function Get-Numbers {
    1
    2
    3
}

# Call the function
$result = Get-Numbers
Write-Host "The numbers are: $result"

Output:

The numbers are: 1 2 3

If you want the return values as an array:

$result = @(Get-Numbers)
Write-Host "The numbers are: $($result -join ', ')"

Output:

The numbers are: 1, 2, 3

Suppressing Output

If you don’t want certain values to be returned, suppress them using Out-Null or enclosing them in parentheses.

function No-Output {
    "This won't be returned" | Out-Null
    return "This is the return value"
}

# Call the function
$result = No-Output
Write-Host $result

Output:

This is the return value

Conclusion

In PowerShell:

  1. Use return for explicit returns.
  2. Output is implicitly returned unless suppressed.
  3. Multiple values can be returned as a collection.
  4. Use Out-Null to suppress unwanted output.
See also  Get Hostname from IP Address

This flexibility makes PowerShell functions versatile and efficient for a variety of use cases.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x