PowerShell using the return statement to exit the function example _powershell

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.