Functions
The highest level of automation is functions
, which are self-defined commands that internally use all of the PowerShell mechanisms.
What is Function?
So, a function
is a list of PowerShell statements that has a unique name
that you assign. When you run a function, you type the function name. The statements in the list run as if you had typed them at the command prompt.
Functions can be as simple as:
function Get-PowerShellProcess
{ Get-Process PowerShell }
A function can also be as complex as a cmdlet or an application program.
Function Parameters
Like cmdlets, functions can have parameters
. The parameters can be named, positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline.
The following example is a function called Get-SmallFiles
. This function has a $Size parameter. The function displays all the files that are smaller than the value of the $Size parameter. Because we want files only we filter folders away.
function Get-SmallFiles {
Param($Size)
Get-ChildItem $HOME | Where-Object {
$_.Length -lt $Size -and $_.PsIsContainer -ne $True}
}
To call this function, just type the following command, remember pass the argument for the function.
Get-SmallFiles -Size 500
Function Return Value
Functions can return values
that can be displayed, assigned to variables, or passed to other functions or cmdlets. You can also specify a return value using the return keyword. The return keyword does not affect or suppress other output returned from your function. However, the return keyword exits the function at that line.