This is an example of a function which returns a string. In the example, the function is called in a statement assigning a value to a variable. The value in this case is the return value of the function.
function Get-Greeting{
"Hello World"
}
# Invoking the function
$greeting ...
A function can be defined with parameters using the param block:
function Write-Greeting {
param(
[Parameter(Mandatory,Position=0)]
[String]$name,
[Parameter(Mandatory,Position=1)]
[Int]$age
)
"Hello $name, you are $age years old."
}
...
Parameters to a function can be marked as mandatory
function Get-Greeting{
param
(
[Parameter(Mandatory=$true)]$name
)
"Hello World $name"
}
If the function is invoked without a value, the command line will prompt for the value:
$greeting = Get-Greeting
...
This is a copy of the advanced function snippet from the Powershell ISE. Basically this is a template for many of the things you can use with advanced functions in Powershell. Key points to note:
get-help integration - the beginning of the function contains a comment block that is set up to be ...
There are a variety of ways to validate parameter entry, in PowerShell.
Instead of writing code within functions or scripts to validate parameter values, these ParameterAttributes will throw if invalid values are passed.
ValidateSet
Sometimes we need to restrict the possible values that a paramet...