【问题标题】:How do I debug a powershell script executed from C#?如何调试从 C# 执行的 powershell 脚本?
【发布时间】:2015-09-27 14:48:42
【问题描述】:

虽然在 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 脚本并每 2 行放置一个 Write-Host $somevariable,来逐步调试此脚本?

我应该提到脚本本身不能独立运行,C# 代码将变量添加到脚本的运行空间。

【问题讨论】:

  • 也许使用调试器“附加到进程”可能是一种方法......但不确定调试器是否以及如何找到脚本的源代码......也许是 DebugBreak().. .某处?
  • 不是 C# 向脚本中添加变量,而是让那些东西成为脚本参数;那么你就可以独立使用脚本了。

标签: c# powershell


【解决方案1】:

可以使用脚本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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-09
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2020-08-12
    • 2010-10-20
    • 1970-01-01
    相关资源
    最近更新 更多