How can I log from a PowerShell function without messing up my Boolean returns?

August 24, 2025 1 answer
Asked by _ask_a_physicist_
Hey everyone, I'm trying to set up a PowerShell function that logs its activity for auditing and troubleshooting while still returning a clean Boolean result. The function will be running as a scheduled task on Windows EC2 servers, and I'm facing some challenges: - I want it to log decision-making steps to a transcript or log file without breaking the Boolean return value. - When I use `Write-Output`, it combines log messages with the Boolean return, which messes up my conditional logic (like in `if (-not (Test-FridayAfterPatchTuesday))`). However, if I rely only on `Write-Host`, I risk losing logs during execution in a non-interactive environment. Here's a basic function I've been working with that demonstrates the issue: ```powershell function Test-PatchFriday { Write-Output "Checking if today is Patch Friday" # Simulate calculation... $isPatchFriday = $false Write-Output "Decision: $isPatchFriday" return $isPatchFriday } $result = Test-PatchFriday Write-Output "Function returned: $result" Write-Output "Type: $($result.GetType().Name)" Write-Output "IF test: $((-not $result))" ``` This results in `$result` being an array instead of just a Boolean. What's the best practice to achieve proper logging while keeping a clean Boolean return? Should I use something like `[void](Write-Output ...)`, or is there a better solution for logging in scheduled tasks?

Answers

FIRST VIOLIN
Try using `Write-Verbose` instead. Setting `$VerbosePreference` to `Continue` will let verbose messages be captured in the transcript file when you use `Start-Transcript`. Just make sure to include `-Verbose` when you call your function to see those messages in the log! Example: ```powershell $VerbosePreference = "Continue" Write-Verbose -Message "Your message here" ```

_slow_down_a_bit_: Does this work well with thread jobs, though?

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions