Powershell function that returns value and produces debug output
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 开发者_如何学Python 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.
In my scripts I use a Write-Log function which writes it's input using out-file and will optionally write to the screen with Write-Host:
Write-Log -Message $MyMessage -Path $MyLog -WriteHost
This approach does not capture messages written to stderr like Start-Transcript but you can control what is written to the log. I often combine both techniques when debugging.
Tee-Object
is your friend.
get-process | tee-object -filepath C:\Test1\testfile2.txt
Here is how I used tee in my script:
Function display {
Write-Output "Testing"
return 20
}
Function CallAnother {
Display
}
CallAnother | Tee-Object "C:\DropBox\Scripts\Test.log"
And, this the output at my console and test.log:
Testing
20
精彩评论