2012-04-15 50 views
1

是否有方法將調試消息從PowerShell函數打印到控制檯並返回值?從PowerShell函數將調試消息打印到控制檯,返回

例子:

function A 
{ 
    $output = 0 

    # Start of awesome algorithm 
    WriteDebug # Magic function that prints debug messages to the console 
    #... 
    # End of awesome algorithm 

    return $output 
} 

# Script body 
$result = A 
Write-Output "Result=" $result 

有沒有符合這個規則的一個PowerShell功能?

我知道Write-Output和Write- *,但在所有我的測試中,使用上述函數中的任何函數都不會寫入任何調試消息。我也知道,只是調用函數而不使用返回的值將確實導致函數編寫調試消息。

回答

6

當然,請使用Write-Debug cmdlet來完成此操作。請注意,默認情況下,您不會看到調試輸出。爲了看到調試輸出,將$DebugPreference設置爲Continue(而不是SilentlyContinue)。對於簡單的功能,我通常會做這樣的事情:

function A ([switch]$Debug) { 
    if ($Debug) { $DebugPreference = 'Continue' } 
    Write-Debug "Debug message about something" 
    # Generate output 
    "Output something from function" 
} 

請注意,我不建議使用格式return $output。函數輸出任何未被變量捕獲的內容,重定向到文件(或Out-Null)或投射到[void]。如果您需要儘早從功能中返回,那麼請儘量使用return

對於先進的功能,你可以多一點輕鬆搞定調試功能,因爲PowerShell中爲您提供了無處不在的參數,包括-Debug

function A { 
    [CmdletBinding()] 
    param() 

    End { 
     $pscmdlet.WriteDebug("Debug message") 
     "Output something from cmdlet" 
    } 
} 

僅供參考,它是在param()聲明[CmdletBinding()]屬性是什麼使這一個先進的功能。

如果您只想輸出與調試無關的其他信息,請不要忘記Write-Verbose$pscmdlet.WriteVerbose()

+2

寫主機的作品也是如此。 – x0n 2012-04-15 15:45:14

+3

@ x0n嗯,除了你沒有太多的控制消息到主機。沒有關閉它們,也沒有重定向到日誌文件。 :-) – 2012-04-16 16:49:47

+0

我現在看到了。謝謝。 – 2012-04-18 18:50:27