This article describes that when you customize the PowerShell function, you can use the return statement to exit the function, and the returns statement can also give the caller the value to the function.
Use the return statement to exit the function directly. Look at an example of an exit Function:
Copy Code code as follows:
function get-namedprocess
{
Param
($name = $null)
if ($name-eq $null)
{
Write-host-foregroundcolor Red ' Specify a name! '
Return
}
Get-process $name
}
The above get-namedprocess requires you to enter the name of a process, and then the function will output information about the process. If the process name is not entered at the time of the call, a prompt should pop up and the function is exited. Very well understood! In this function, return is so bare that you can simply exit the function.
Returns can actually return a value to the caller of the function. Look at an example:
Copy Code code as follows:
function convertto-binary
{
Param ($Number)
return [System.convert]::tostring ($Number, 2)
}
The function is to convert the input numbers into binary strings. The execution of the call is as follows:
Copy Code code as follows:
Ps> Convertto-binary-number 123
1111011
Finally, to explain, a function of the return value, in fact, should not be returned all the same. As long as the output in the function is used as the return value to the function. Look at the following function:
Copy Code code as follows:
function convertto-binary
{
Param ($Number)
"Original Number: $Number"
[System.convert]::tostring ($Number, 2)
Return
}
The output results are as follows:
Copy Code code as follows:
Ps> Convertto-binary-number 123
Original number:123
1111011
About PowerShell function Exit Function statement, this article introduces so many, hope to help you, thank you!