c# - 如何调试从 C# 执行的 powershell 脚本?

标签 c# powershell

我有代码通过在 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# 代码将变量添加到脚本的运行空间。

最佳答案

脚本可以实现 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.

关于c# - 如何调试从 C# 执行的 powershell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32787447/

相关文章:

windows - 使用 PowerShell 脚本以分钟为单位查找时差

powershell - Enable-WindowsOptionalFeature -Online from powersell as admin 失败

string - 从PowerShell中的绝对路径获取相对路径

c# - 如何使在 Azure 实例中运行的 ASP.NET WebAPI 程序每分钟更新一次数据库?

sql-server-2008 - 在 Powershell 中添加 SQL Server 注册服务器

C# Linq To SQL 填充 DataGrid 并将字段放入 TextBox

c# - 在 web.config 中指定相对文件位置以供标准 C# 类库使用

.net - 使用 PowerShell/C# 从 cmd 批处理保存文件对话框

c# - 泛型确保 T 属于指定的 N 个类中的任何一个

c# - 使用 BouncyCaSTLe 签署 X509 证书 - 无效的数字签名