I'm writing a Powershell function that is used inside a .ps1 script I am writing.
The function returns a single number that is used by the function that calls it inside the script. While developing it, I would like the function to output debug info (plain old strings).
Sometimes I just want the debug output to show up on the screen, sometimes I'd like to capture it in a file (which I assume I'll do with either
.\myscript.pl1 > file.txt
or
.\myscript.pl1 2> file.txt
Is there any way to do this?
Mike, I want to try write-log, but on my system I have:
D:\library>gcm write* CommandType Name ----------- ---- Alias write Application write.exe Application write.exe Cmdlet Write-Debug Cmdlet Write-Error Cmdlet Write-EventLog Cmdlet Write-Host Cmdlet Write-Output Cmdlet Write-Progress Cmdlet Write-Verbose Cmdlet Write-Warning
If I understand you this time, you can do something like this:
start-transcript -path debug.txt
write-debug "blah"
stop-transcript
So when you don't want any kind of output, leave $debugpreference="SilentlyContinue"
When you do want the output, set it to Continue
Only thing is that the file will have the extra noise for transcript.
Give this a try and see if it helps
Set-Variable -Name DebugPreference -Value 'Continue'
$outFile = 'C:\tmp\debug.out'
function calledFunction {
if ($outFile) {
"`nIn Called Function" | Out-File $outFile -Append
Write-Debug "In called function IF"
return 1
}
else {
Write-Debug "In called function ELSE"
return 900
}
}
function callingFunction {
$returnCount = calledFunction
if ($outFile) { "`nReturn Count is $returnCount" | Out-File $outFile -Append }
Write-Debug "Return Count is $returnCount"
$outFile = $null
if ((calledFunction) -gt 10) { Write-Debug "outFile is not set" }
}
callingFunction
As it is the write-debug will write to the console. When you don't want to see those messages just change the Value for DebugPreference in the first line to 'SilentlyContinue'.
When you don't want output going to the debug.out file just comment out that line or set it to $outFile = $null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With