This article describes how to get a function to return a value when customizing the PowerShell function, how to receive a return value, and how to keep irrelevant content from being placed in an array of return values.
Any output in the body of the PowerShell function, in general, is returned to the function caller as a return value. The contents of multiple outputs are placed in an array of return values.
For example, there is a function of the return value test,
Copy Code code as follows:
function Test-returnvalue
{
1
' Hello '
Return get-date
}
This function defines three return values, and the effect of the invocation is as follows:
Copy Code code as follows:
Ps> Test-returnvalue
1
Hello
Saturday, November 2, 2013 12:52:13
ps> $result = Test-returnvalue
Ps> $result [0]
1
As can be seen from the above call, the direct call will be like an array, divided into three rows to output each return value. And when we use a change $result to save the return value, we can see that the return value of the function is an array, starting with subscript 0 and 0-2 being the subscript of three elements.
Let's say that if you want the function to have some hint of output, but do not want to let these outputs are placed in the function's return value, how should it be implemented? Microsoft recommends that we use Write-host or write-warning, and that the output from these two cmdlet will be displayed directly to the console console without entering the array of return values.
We modify the function above to add two lines of prompt output.
Copy Code code as follows:
function Test-returnvalue
{
#加一句Write-host
Write-host ' starting '-foregroundcolor Green
1
' Hello '
#再加一个Write-warning
Write-warning ' almost done ... '
Return get-date
}
And then look at the execution effect,
Copy Code code as follows:
Ps> Test-returnvalue
Starting
1
Hello
Warning:almost done ...
Saturday, November 2, 2013 12:54:11
ps> $result = Test-returnvalue
Starting
Warning:almost done ...
One is a direct call, one is the assignment call, do you see the difference? Write-host and Write-warning, what is called direct output to the console!
About the return value of the PowerShell function, this article on the introduction of so many, I hope to help you, thank you!