簡體   English   中英

如何調試從C#執行的powershell腳本?

[英]How do I debug a powershell script executed from C#?

我通過在C#中使用System.Management.Automation命名空間運行PowerShell腳本的代碼,類似於下面的代碼。

 using (mPowershell = PowerShell.Create()) 
 {
        mPowershell.AddScript(GetScriptText(mStep), true);
        SetPowershellVariables(mPowershell);
        output = new PSDataCollection<PSObject>();
        output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded);
        mPowershell.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged);
        IAsyncResult asyncResult = mPowershell.BeginInvoke<PSObject, PSObject>(null, output);      
}

正如所料,我遇到了錯誤,我想調試它們。

有沒有辦法,沒有進入powershell腳本並每兩行放一個Write-Host $somevariable ,一步一步調試這個腳本?

我應該提一下腳本本身不能獨立運行,C#代碼將變量添加到腳本的運行空間中。

可以使用腳本Add-Debugger.ps1 UI非常原始,只是一個輸入對話框和一個輸出控制台,您必須在腳本中添加一些臨時代碼才能進行調試。 但是,如果沒有更好的選擇,這樣的調試器仍可以正常工作。

要添加到腳本以添加和觸發調試的臨時代碼

# Add debugger with file output shown in a separate console.
# <path\> may be omitted if Add-Debugger.ps1 is in the path.

<path\>Add-Debugger.ps1 $env:TEMP\debug.log

# set some breakpoints
$null = Set-PSBreakpoint ...

從現在開始,當觸發斷點時,將顯示調試器輸入框。 鍵入命令,檢查變量,在輸出控制台中查看輸出。 可用命令集:

s, StepInto  Step to the next statement into functions, scripts, etc.
v, StepOver  Step to the next statement over functions, scripts, etc.
o, StepOut   Step out of the current function, script, etc.
c, Continue  Continue operation (also on empty input).
q, Quit      Stop operation and exit the debugger.
?, h         Write this help message.
k            Write call stack (Get-PSCallStack).
K            Write detailed call stack using Format-List.

<n>          Write debug location in context of <n> lines.
+<n>         Set location context preference to <n> lines.
k <s> <n>    Write source at stack <s> in context of <n> lines.

w            Restart watching the debugger output file.
r            Write last PowerShell commands invoked on debugging.
<command>    Invoke any PowerShell <command> and write its output.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM