2011-07-29 29 views
2

我正在寫一個Powershell函數,用在我寫的.ps1腳本中。Powershell函數返回值併產生調試輸出

該函數返回由腳本內調用它的函數使用的單個數字。在開發它的時候,我想要輸出調試信息的函數(普通的舊字符串)。

有時候,我只是想調試輸出顯示在屏幕上,有時我想捕捉它在一個文件中(我以爲我會做任何

.\myscript.pl1 > file.txt 

.\myscript.pl1 2> file.txt 

有沒有辦法做到這一點


邁克,我想嘗試寫日誌,但是我的系統上我有:

 
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 
+0

思考更多,我敢打賭我沉沒了。我習慣於可以寫入STDOUT並返回值的函數,這兩件事情是不同的。它們在Powershell中總是一樣嗎? – JonathanZ

+1

當然不是。例如,比較'Write-Output'和'Write-Host'。還有'Write-Debug','Write-Warning','Write-Error'和'Write-Verbose'。 PowerShell有大量的流,'Write-Output'是唯一一個進入流水線的流。 – Joey

+0

Joey-有沒有這些默認的屏幕,可以重新定向到一個文件? – JonathanZ

回答

0

Tee-Object是你的朋友。

get-process | tee-object -filepath C:\Test1\testfile2.txt 

這裏是我用發球在我的腳本:

Function display { 
    Write-Output "Testing" 
    return 20 
} 

Function CallAnother { 
    Display 
}  

CallAnother | Tee-Object "C:\DropBox\Scripts\Test.log" 

而且,這個輸出在我的控制檯和test.log中:

Testing 
20 
+0

我在函數中寫入字符串的內容是什麼?我試過寫主機和寫輸出。第一個不會重定向,第二個會被函數返回給調用函數。 – JonathanZ

+0

我更新了我的答案。看看這是否適合你! – ravikanth

+0

對於我的問題,Display必須將值返回給CallAnother。我沒有看到你的例子。 – JonathanZ

1

如果我理解你此時,你可以這樣做:

start-transcript -path debug.txt 
write-debug "blah" 
stop-transcript 

所以,當你不希望任何類型的輸出,離開$debugpreference="SilentlyContinue"

當你想要的輸出,將其設置爲Continue

唯一的是,該文件將對成績單額外的噪音。

0

在我的劇本我使用寫日誌功能,將其寫入使用輸入了文件,將選擇寫使屏幕與寫主機:

寫日誌-Message $ MyMessage -Path $ MyLog - WriteHost

此方法不會捕獲寫入stderr的消息(如Start-Transcript),但您可以控制寫入日誌的內容。調試時,我經常結合這兩種技術。

+0

原來的問題附加了長的評語^^^^ – JonathanZ

+0

我發現了這個:http://poshcode.org/2566。我猜這是你正在使用的。 – JonathanZ

1

試試這個,看看它是否有助於


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 

,因爲它是寫調試將寫入控制檯。當您不想看到這些消息時,只需將第一行中的DebugPreference的Value更改爲'SilentlyContinue'即可。

如果您不想輸出到debug.out文件,只需將該行註釋掉或將其設置爲$ outFile = $ null即可。