Powershell function Return Value Problems

Source: Internet
Author: User
Tags true true

 

Powershell function Return Value Problems

The function return value of powershell is significantly different from that of other scripting languages. I have been studying it for a while before I can understand what is going on.

First, you need to understand what is "Default output". The default output means that no specific output device statement is specified to be output. It is equivalent to stdout of a traditional programming language or shell, but it is actually called standard output. The statement is as follows:

Ps c:/users/Administrator> 1 + 1
2
Ps c:/users/Administrator>

1 + 1 is an expression with the result of 2. If we do not specify the output location, the system will throw it to "Default output" or "standard output, the default output is simply to display it back.

Another example is:

Ps c:/users/Administrator> $ x = "Hello world! "
Ps c:/users/Administrator> $ x
Hello world!
Ps c:/users/Administrator>

Similarly, the $ X variable does not specify any left value, so it is also thrown to the standard output to display the value of the variable.

Now let's take a look at the function return value in powershell. The function return value of powershell is the value of all outputs in the function body, rather than the value specified by the Return Statement.

That is to say, any value in the function body to the standard output is part of the return value.

For example, this function:

Function test1 ()
{
"ABC"
}

According to the traditional programming or script idea, there is no return statement here, and there should be no return value, but the result of running this function is:

Ps c:/users/Administrator> test1
ABC
Ps c:/users/Administrator>

According to the traditional ideas, this method is very difficult, and it seems that there is no need to play like this. There are also countless problems to play. Let's come one by one.

First question:There should be only one returned value. Follow this method. Isn't there a few returned values if I put them in a few variables? What should I do in the future when such chaotic function returns?

Answer:There is indeed only one return value, but it is also true that you will return what you output, so the result is that the return value is a large array, which contains all the output in the function. Do not believe this function Test2:

Function Test2 ()
{
"ABC"
"Def"
123
}

View the execution result of this function:

Ps c:/users/Administrator> Test2
ABC
Def
123
Ps c:/users/Administrator>

We can also save the execution result to the variable and call the GetType () method to learn the returned object type:

Ps c:/users/Administrator> $ result = Test2
Ps c:/users/Administrator> $ result. GetType ()

Ispublic isserial name basetype
-----------
True true object [] system. Array

We can see that array is indeed returned.

Second question:Is there a way to specify the return value type? I still expect to continue to process the returned data. If such a large package array is lost, will it be difficult for future work?

Answer:There is no trouble at all. In fact, the returned data is completely stored in the original data type, and there is no obstacle in processing. Please refer to the test1 and Test2 functions just now:

Ps c:/users/Administrator> $ result = test1
Ps c:/users/Administrator> $ result. GetType ()

Ispublic isserial name basetype
-----------
True true string system. Object

Ps c:/users/Administrator> $ result = Test2
Ps c:/users/Administrator> $ result | % {$ _. GetType ()}

Ispublic isserial name basetype
-----------
True true string system. Object
True true string system. Object
True true int32 system. valuetype

Test1 has only one return item, so you can directly GetType (). We can see that string is passed back. Test2 traverses the entire array because there are three items in array, we can see that two strings and one int32 are completely saved. In fact, the object type in any. Net class library or even the custom object type can be passed here. There is no problem at all.

Third question:Some outputs I don't want to put them in the return value. What should I do? For example, the following function:

Function test3 ()
{
USD due = 1000
Write-output "your prepayment balance is :"
Write-output $ due
}

The output result is:

Ps c:/users/Administrator> test3
Your prepayment balance is:
1000

If you want to extract 1000 from the function result at the beginning, you have to unbind the array and obtain the second value. This is too much trouble. You might as well skip the function. Just as you must:

Ps c:/users/Administrator> $ x = test3
Ps c:/users/Administrator> $ x
Your prepayment balance is:
1000
Ps c:/users/Administrator> $ X [1]
1000

This is too frustrating. We need to allow the function to output information, and let the final result return the desired value and remove the prompt information. What should we do?

Answer:Write the function so that the output statement is replaced by write-Host:

Function test3 ()
{
USD due = 1000
Write-host "your prepayment balance is :"
Write-output $ due
}

Let's look at the function output:

Ps c:/users/Administrator> test3
Your prepayment balance is:
1000
Ps c:/users/Administrator> $ x = test3
Your prepayment balance is:
Ps c:/users/Administrator> $ x
1000
Ps c:/users/Administrator>

You can see that the prompt statement is output during the function runtime, but is not included in the return value. In fact, write-host refers to the screen output, while write-output refers to the output to the standard output. Of course, if write-output is omitted, it is also output to the standard output.

Fourth question:Some cmdlet/fuction/method has the returned value. Sometimes we only need to execute the cmdlet/function/method itself, and do not need the returned value, at this time, the returned value will be captured by our outer function and returned. What should I do? For example, if there is such a function test4, I want to obtain the current directory and list the files in the directory. This is very simple:

 

Function test4 ()
{
PWD
Dir
}

The problem is that PWD returns the directory object of the current directory, and Dir also returns the object of the current directory. In this way, the returned value has two current directories. What should we do if we only need one? If you change it to write-host Dir, the result is also comedy. You can directly output the three letters "dir.

Answer:There will be a solution for a moment:

Function test4 ()
{
PWD
$ Temp = dir

Write-host $ temp
}

It all requires temporary variables. Isn't it silly? In addition, if it is not dir but a call that takes a long time to complete and has a long output call, it would be silly to use a variable that is useless at all.

However, if it is not a cmdlet or something like a method, you can add [void] before the method call to enable it to have no return value. In most cases, this type should be used. To illustrate this usage, we need a slightly more complex example. The previous stupid usage cannot explain this problem. I borrowed an example of performance counter calling in powershell cookbook, as shown below:

Function getcounter ()
{
$ Arguments = "system", "system up time"
$ Counter = new-Object System. Diagnostics. performancecounter $ arguments
[Void] $ counter. nextvalue ()
New-object timespan 0, 0, 0, $ counter. nextvalue ()

}

 

According to the. NET class library, nextvalue must be called twice to get the correct result. Therefore, we can add [void] before the first call to avoid extra return values.

Fifth question:I strongly want to continue using the return keyword to limit the return value. Is there a solution?

Answer: Unfortunately, there is no solution. Although powershell supports the return keyword, the function behavior will not be affected. For example:

Function test5 ()
{
"ABC"
$ X = "def"
Return $ x
}

The running result of test5 is as follows:

Ps c:/users/Administrator> test5
ABC
Def
Ps c:/users/Administrator>

We still need to output all the variables in ABC and return. In fact, there is no difference between return and write-oupput.

This is a very unpleasant feature of functions in powershell. To be honest, it would be quite comfortable to be involved with functions for the first time, but for people with experience in other programs and scripts, this feature is a little lame.

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.