M.K.
M.K.

Reputation: 169

Ensure only intended objects passed from a function down to the pipeline

I have a complex function (not one liner) that receives an object, does some staff, and then it should return the same object back to the pipeline.

The function body opens files for writing, downloads something from the web service, etc. It also provides feedback to users by printing to console.

function($obj)
{
     do some staff
     more staff
     $obj
}

How do I ensure that only intended objects are returned back to the pipe line and nothing else like the text printed to the console or something that could be printed from the commands I run in the function body?

I think Write-Host should not impact the pipeline. But not sure about other commands. Perhaps, there is some way to do it. Did not find anything yet.

Upvotes: 2

Views: 55

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174785

One strategy could be to wrap the function body in a separate block, dot-source it but suppress all output from it and then return whatever variable you need returned from outside the main block:

function Do-Stuff
{
  param($obj)

  $null = . {
    Get-Random
    $obj.Stuff = "Modified"
    Write-Output "All sorts of noise"
  }
  return $obj
}

Now you can do:

PS C:\> Do-Stuff -obj ([pscustomobject]@{Name="MyObject";Stuff="Original"})

Name     Stuff
----     -----
MyObject Modified

and only $obj is returned, everything else is swallowed by $null

Upvotes: 2

Manuel Batsching
Manuel Batsching

Reputation: 3606

Only the output stream will be passed to the pipeline. If you handle your console output with cmdlets like Write-Verbose, Write-Warning or (if you must) Write-Host, they will not interfere with the pipeline.

If you are using cmdlets with return values, that you do not wish to pass to the output stream or to a variable, you can pipe them to Out-Null as an option.

Upvotes: 0

Related Questions