Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another PowerShell function return value and Write-Output

Tags:

powershell

this has been beaten to death but can't find an exact solution for my problem.

I have a PowerShell script that can be run from the command line or from a scheduled task. I'm using the following line

Write-Output "Updating user $account" | Tee-Object $logfile -Append

to write relevant information to the screen and a log file. I need both because when run from a command line, I can physically see what's going on but when run from a scheduled task, I have no visibility to its output hence the log file.

Thing is, I'm modifying my code to use functions but as you might already know, Write-Output messes up the return values of functions when used within said functions.

What could I do that would do something similar to what I stated above without affecting the function's return value?

Thanks.

like image 827
Sylvain Avatar asked May 19 '26 12:05

Sylvain


2 Answers

Just write to a log file. When running from the console, open another console and tail the log file.

Get-Content 'C:\path\to\the\logfile.txt' -Tail 10 -Wait
like image 56
lit Avatar answered May 21 '26 06:05

lit


Assuming PowerShell version 5 or higher, where Write-Host writes to the information output stream (stream number 6), which doesn't interfere with the success output stream (stream number 1) and therefore doesn't pollute your function's data output:

The following is not a single command, but you could easily wrap this in a function:

Write-Host "Updating user $account" -iv msg; $msg >> $logfile

The above uses the common -InformationVariable (-iv) parameter to capture Write-Host's output in variable $msg (note how its name must be passed to -iv, i.e. without the leading $).

The message captured in $msg is then appended to file $logfile with >>, the appending redirection operator.

  • Note: >> is in effect an alias for Out-File -Append, and uses a fixed character encoding, both on creation and appending.
  • Use Add-Content and its -Encoding parameter instead, if you want to control the encoding.
like image 29
mklement0 Avatar answered May 21 '26 05:05

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!