excel - powershell:如果 excel 已经在运行,则获取实例,否则启动它 - 带有异常处理

标签 excel com powershell exception-handling

使用 Powershell,我想将一些制表符分隔的 Ascii 文件导入 MS Excel。为此,我使用了一个循环,现在我有一个简单的解决方案:

for each file: start Excel , import tsv file, close Excel. 

..假设 Excel 在路径中,它是 Excel 的正确版本,Excel 2010

现在我想切换到更高效的版本:保持 excel 打开。

对于每个文件:如果有,则抓取正在运行的 excel 实例,如果没有,请尝试启动 excel。处理文件。保持excel打开。最后,保持打开状态(我想在脚本运行时查看 excel 文件,这可能需要一段时间。令人讨厌的是,在当前版本的脚本中,当我查看输出时,excel 正在关闭)。

我还没有找到一个全面的解决方案,无论是这里还是互联网上的其他地方。 “全面”是指“异常处理”。在 Powershell 中,这有点令人困惑。有两种处理异常的方法:使用陷阱和 try-catch block 。

这是我的代码,来自几个互联网资源,我该如何改进它?

我想将它包装在一个函数中,但是将 COM 对象作为返回值是有问题的。 (
我想要的是“简单工厂”和“单例”的组合。)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel")
    try { 

        $excelApp = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application") 


    } catch [System.Runtime.InteropServices.COMException], [System.Management.Automation.RuntimeException]{

         write-host              
         write-host $("TRAPPED: " + $_.Exception.GetType().FullName);
          write-host $("TRAPPED: " + $_.Exception.Message);
          write-host "Excel is not running, trying to start it";

          $excelApp = New-Object -ComObject "Excel.Application"
          if (-not $excelApp){ 
              # excel not installed, not in path
              Write-Error "Excel not running, and cannot be started, exiting."
              # Todo: test if excel version is correct, e.g. english Excel 2007 or 2010., if not set outfile extension xls.
              exit;
          }             
    }

    catch [System.Exception]{
        write-host $("EXCEPTION: " + $_.Exception.GetType().FullName);
        write-host $("EXCEPTION: " + $_.Exception.Message);c
        Write-Error 'Something went wrong during creation of "Excel.Application" object, => Exit.'
        exit;
    }

最佳答案

你问这个已经有一段时间了,但我遇到了同样的问题。您的代码似乎只是合理解决方案的一个很好的例子。不过,我确实质疑你的担忧。具体来说,一旦 Excel 运行,是否需要在函数中再次调用此例程?也就是说,一旦 Excel 打开,您就可以将其视为打开/关闭工作簿、访问其中的工作表以及最终 $excelApp.Quit() 应用程序的服务(尽管在 Powershell v1.0 中 .Quit() 获胜'不要退出应用程序......但这没关系,因为无论如何我都在抓取一个正在运行的实例)。

下面的链接讨论了一种启动和获取 Excel 实例的 PID 的方法,以便在需要时显式地杀死它。

Discussion on Quiting/Killing Excel from within Powershell

关于excel - powershell:如果 excel 已经在运行,则获取实例,否则启动它 - 带有异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6745180/

相关文章:

PowerShell 作业,写入文件

Excel:将单元格的背景颜色更改为该单元格中写入的 RGB 颜色

objective-c - objective-c 是否遵循操作顺序(Bedmas)?

excel - 需要将一个单元格中的文本字符串的数据与另一个单元格中的一列数据进行比较

c++ - 从 BSTR 转换为 char*

com - 64位COM(ActiveX)服务器

powershell - 错误处理 - PowerShell 脚本

c++ - 从 Windows XP 32 位迁移到 Windows 7 64 位的 Excel 插件错误

delphi - Delphi有 "getopt"的实现吗?

powershell - 是否有相当于 `paste` 的 PowerShell(即水平文件连接)?