【问题标题】:How to extract $lastexitcode from c# powershell script execution如何从 c# powershell 脚本执行中提取 $lastexitcode
【发布时间】:2010-10-20 10:21:09
【问题描述】:

我在这里的代码项目中使用 powershell 异步执行代码在 C# 中执行了一个 scipt:

http://www.codeproject.com/KB/threads/AsyncPowerShell.aspx?display=PrintAll&fid=407636&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2130851#xx2130851xx

我需要返回 $lastexitcode,Jean-Paul 描述了如何使用自定义 pshost 类返回它。我在 pshost 中找不到任何返回退出代码的方法或属性。

我拥有的这个引擎需要确保脚本正确执行。

任何帮助将不胜感激。

问候 鲍勃。

它的 $lastexitcode 和 $?我需要带回来的变量。

嗨, 终于回答了。
我发现了 $host 变量。它实现了对主机的回调,特别是自定义 PSHost 对象,使您能够返回 $lastexitcode。这是 $host 解释的链接。

http://mshforfun.blogspot.com/2006/08/do-you-know-there-is-host-variable.html

与 powershell 文档一样,它似乎晦涩难懂,文档也很糟糕。使用第 4 点,调用 $host.SetShouldExit(1) 将 1 返回到 pshost 的 SetShouldExit 方法,如此处所述。

http://msdn.microsoft.com/en-us/library/system.management.automation.host.pshost.setshouldexit(VS.85).aspx

这实际上取决于定义您自己的退出代码定义。我猜是 0 和 1 后缀。

问候 鲍勃。

【问题讨论】:

    标签: c# powershell scripting exit-code pshost


    【解决方案1】:

    这是一个你可以尝试的功能:

    function run-process ($cmd, $params) {
    $p = new-object System.Diagnostics.Process
    $p.StartInfo = new-object System.Diagnostics.ProcessStartInfo
    $exitcode = $false  
    $p.StartInfo.FileName = $cmd
    $p.StartInfo.Arguments = $params
    $p.StartInfo.UseShellExecute = $shell
    $p.StartInfo.WindowStyle = 1; #hidden.  Comment out this line to show output in separate console
    $null = $p.Start()
    $p.WaitForExit()
    $exitcode = $p.ExitCode
    $p.Dispose()    
    return $exitcode
    }
    

    希望有帮助

    【讨论】:

      【解决方案2】:

      您可以在脚本代码中编写将检查 $lastexitcode 并在退出代码不是您例外的情况下throw an exception。
      异常更容易捕获。

      【讨论】:

      • 好吧好吧。我看过陷阱。我会检查一下。我假设它返回到 c# 运行时,通过错误集合返回。
      • 嗨 Shay,如果 $?代码是假的。
      • 你的意思是这样的: if ($lastexitcode -eq 0) throw (new-object system.Exception("Error")
      【解决方案3】:

      我相信您正在通过使用此代码项目从小山中翻山越岭。异步执行在 C# 中很容易做到。

      PowerShell psCmd = PowerShell.Create().AddScript({Invoke-YourScriptAndReturnLastExitCode});
      IAsyncResult result = psCmd.BeginInvoke();
      // wait for finish
      psCmd.EndInvoke(result);
      

      此外,查看您对该项目的问题,您似乎正在尝试在 PowerShell 中使用 TFS。您可以考虑以下附加信息:

      1. TFS has cmdlets
      2. 许多其他人使用过 TFS cmdlet,即PSTFS
      3. 您可以随时将 tfs 可执行文件复制到您需要的任何位置,这至少可以避免部分脚本的痛苦。

      希望对你有帮助

      【讨论】:

      • 嗨 MediaAndMicrocode,我从未使用过 lances 代码。我使用了与上述方法类似的方法,除了更健壮之外,我使用了生产者/消费者队列,其中每个队列条目都是一个 pshell 执行块,队列由多个线程提供服务。线程将执行块出列并选择多个 pshell 执行引擎中的一个,具体取决于它们是否被 Autoresetevent 阻塞。它工作正常,性能卓越,正是我想要的。谢谢您的帮助。鲍勃。
      • 我现在会使用 TPL 和上面的。
      猜你喜欢
      • 2018-11-09
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2020-08-12
      相关资源
      最近更新 更多