How can I log in a PowerShell function without affecting its Boolean return value?

0
2
Asked By CuriousCoder92 On

Hey everyone,

I'm working on a PowerShell script that runs as a scheduled task on my Windows EC2 servers. I'm trying to create a function that logs the steps it takes for audit and troubleshooting purposes, while still returning a clean Boolean value to use in conditions like `if (-not (Test-FridayAfterPatchTuesday)) { ... }`.

However, I ran into a snag: when I use `Write-Output` for logging, the function ends up returning both log messages and the Boolean value, which messes up my `if` logic. On the other hand, using `Write-Host` keeps the return clean but I've heard that its output might not show in transcript or log files for scheduled tasks, which would mean losing important log information.

Here's the basic structure of my function:

```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"
```

I want to find the best way to log these messages while ensuring my function only returns a Boolean. Any tips? Is using `[void](Write-Output ...)` a good approach, or is there something better for logging in functions designed to return a clean Boolean, especially in a scheduled task context? Thanks!

1 Answer

Answered By TechWiz123 On

You could use `Write-Verbose`, which is compatible with `Start-Transcript`. Just set `$VerbosePreference = 'Continue'` before that. This way, your verbose messages will get logged into the transcript file without affecting the return value of your function.

ScriptKiddy -

Does this method play nicely with thread jobs?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.