Returning values and displaying values in function conditionally -2

Nandan Hegde 32,831 Reputation points MVP
2023-10-18T05:15:11.3066667+00:00

Hello All,

Good day!

This is in accordance to my prev query :

https://learn.microsoft.com/en-us/answers/questions/1386439/returning-values-and-displaying-values-in-function

where a function can be called implicitly or explicitly and accordingly the output should either be print or just return value.

In this query , my ask is the other way as to how to ensure only Print statements are executed and the return value is not displayed when the function is called individually.

FUNCTION TEST1
{

 

$x= "1","2","3"

 

for ($i=0;$i-lt $x.length;$i++)
{
write-host "This is " $x[$i]
}

 

return $x

 

}

So based on above scenario, the ask is when the function is called individually, I just need to display the values as

This is 1

This is 2

This is 3

And in case if called within another function for variable initialization, need to return just the values like and ignore the write host part.

1

2

3

How to suppress the return value to be displayed?

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,669 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,386 Reputation points
    2023-11-15T20:39:52.7366667+00:00

    There's no way to do this (at least non that I know of) without passing some indication of what the function should do.

    FUNCTION TEST1
    {
        "1","2","3"
    }
    
    $y = TEST1          # save the values to an array
    TEST1               # just send the returned values to the success stream (NOT a best-practice!)
    $null = TEST1       # discard the returned values
    TEST1 |             # send the returned values to the console host
        ForEach-Object{
            Write-Host "This is $_"
        }
    

    Keep in mind that Write-Host sends the output to the console host, not to your script. It happens immediately, too.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.