【发布时间】:2016-01-23 05:19:24
【问题描述】:
我在 Powershell 中编写了很多脚本,现在想修改一些 Microsoft Word 文档。我注意到我的脚本在某些服务器上运行得很快,而在其他服务器上运行得非常慢。经过进一步分析,似乎对某些用户配置文件使用 Word.Application COMObject 速度很快,但对于同一服务器上的其他一些用户配置文件,它非常慢。
与此同时,我只用几行代码就能重现问题 - 基本上每个方法或操作似乎都受到了影响。
这是我正在做的事情:
- 打开新文档
- 添加一些文字
- 等待 5 秒
- 添加更多文字
没有什么特别的,没有什么火箭科学——但是在 5 秒的停顿之后用文字做任何事情几乎是不可能的。
这是我的代码:
$WordApp1 = New-Object -ComObject Word.Application
$Word1 = $WordApp1.Documents.Add()
$WordApp1.Visible=$true
$selection=$WordApp1.Selection
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
Start-Sleep -Seconds 5
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
(Measure-Command {$selection.TypeText("test")}).TotalMilliseconds
结果是:
77.3065
91.4125
63.3547
80.9694
71.1408
87.1482
10491.071 <----- LOOK HOW LONG IT TOOK
10329.0877 <----- LOOK HOW LONG IT TOOK
为什么会发生这种情况,我该如何避免?
我已经尝试过使用 Bookmarks、Find/Replace 和 MailMerge 并具有相同的奇怪行为。我进行了“修复安装”并重置了 Word 用户设置,但没有改进。
VBA 中的相同代码运行良好且快速,因此必须与 Powershell 或 Word 类有关。 Word 是 2010,Powershell 4.0,服务器 2008R2。发生在多台服务器上,但仅适用于某些用户配置文件。受影响的用户配置文件具有本地管理员权限。
也许它与 Interop.class 有关?也许是一个错误,我需要一个特定的修补程序/补丁?
【问题讨论】:
标签: performance powershell ms-word office-interop com-interop