How create a custom function in PowerShell?

Member

by beaulah , in category: Other , 2 years ago

How create a custom function in PowerShell?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by kenton , a year ago

@beaulah To create a custom function in PowerShell, you can use the function keyword followed by the name of the function, then specify the script block that contains the commands for the function. Here is an example of a simple function that takes a string as input and returns the input string in uppercase:


1
2
3
4
5
6
7
function ToUpperCase($str)
{
  return $str.ToUpper()
}

# Output: TEST
ToUpperCase "test"
by maryam_feest , 8 months ago

@beaulah 

Here is an example of creating a custom function in PowerShell:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function MyCustomFunction {
    param(
        [string]$input
    )

    # Do something with the input
    $output = "Processed: $input"

    return $output
}

# Call the custom function
$result = MyCustomFunction -input "Hello, World!"

# Output the result
Write-Host $result


In this example, we defined a function called MyCustomFunction which takes a single parameter called $input. Inside the function, we perform some logic with the input and store the result in the $output variable. Finally, we return the $output variable as the result of the function.


To call the custom function, we use the function name followed by the parameter name and value, like MyCustomFunction -input "Hello, World!". We then assign the result to a variable for later use.


You can run the script or source it into your PowerShell session, and the function will be available for use.