Here is a minimal function:
function Test-Function
{
"Hello
World!"
}
Calling this places a string of "Hello World!" onto the pipe. You can catch it in a variable if you want or pipe it to some other command. The better way to do it is to use the Write-Output cmdlet. It makes it more clear as to what you are doing do debugging and troubleshooting become easier.
function Test-Function
{
Write-Output
"Hello World!"
}
You can call Write-Output multiple times in a function to return multiple items. You could place it into a loop that runs 10 times and it will output 10 objects. I mention this because Powershell also supports the return keyword but it acts different. When a function gets to any return statement, it exits the function.
function Test-Function
{
return "Hello World!"
}
I prefer Write-Output over return but do use return when it is needed.
I also want to mention that Write-Host is something that you see in scripts from time to time, but it is for host only output. So it is hard to capture into a variable and does not go into the pipe. In most cases, Write-Output is the better choice.
No comments:
Post a Comment