该术语“ ”未被识别为 cmdlet 的名称。

5

我有一个存储在文件中的PowerShell脚本,名为MergeDocuments.ps1。当我从Windows PowerShell命令提示符运行脚本时,它可以正常运行。
.\MergeDocuments.ps1 1.docx 2.docx merge.docx

从Windows控制台应用程序调用该脚本也可以正常运行。

当我尝试从Asp.Net Web服务调用脚本时,遇到了一些有关注册表访问的问题。我使用模拟身份验证并为Network Service帐户授予了对注册表键 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell 的权限来解决此问题。

接下来,我遇到了关于PowerShell无法创建OpenXmlPowerTools.DocumentSource[]类型对象的问题,因此我将以下内容添加到我的脚本中

Add-Type -Path "C:\Users\Administrator\Documents\WindowsPowerShell\Modules\OpenXmlPowerTools\OpenXmlPowerTools.dll"
Import-Module OpenXmlPowerTools

现在的问题是我遇到了错误信息:“未识别cmdlet名称'Merge-OpenXmlDocument'…”

如何解决这个问题?

PowerShell脚本

Add-Type -Path "C:\Users\Administrator\Documents\WindowsPowerShell\Modules\OpenXmlPowerTools\OpenXmlPowerTools.dll"

Import-Module OpenXmlPowerTools

# The last argument is the path of the merged document
$noOfSourceDocs = ($($args.length) - 1)

# Create an array to hold all the source documents
[OpenXmlPowerTools.DocumentSource[]] $docs = New-Object OpenXmlPowerTools.DocumentSource[] $noOfSourceDocs

for ($i = 0; $i -lt $noOfSourceDocs; $i++)
{
    $docs[$i] = New-Object -TypeName OpenXmlPowerTools.DocumentSource -ArgumentList $args[$i]
    $docs[$i].KeepSection = 1
}

Merge-OpenXmlDocument -OutputPath $args[-1] -Sources $docs

WebService .Net代码

using (new Impersonator(username, domain, password))
{
   // create Powershell runspace
   Runspace runspace = RunspaceFactory.CreateRunspace();
   runspace.Open();

   RunspaceInvoke invoker = new RunspaceInvoke(runspace);
   invoker.Invoke("Set-ExecutionPolicy Unrestricted");

   // create a pipeline and feed it the script file
   Pipeline pipeline = runspace.CreatePipeline();
   Command command = new Command(ConfigurationManager.AppSettings["PowerShellScript"]);
   foreach (var file in filesToMerge)
   {
      command.Parameters.Add(null, file);
   }
   command.Parameters.Add(null, outputFilename);
   pipeline.Commands.Add(command);

   pipeline.Invoke();
   runspace.Close();
}

1
我很好奇你为什么要首先从asp.net执行powershell脚本。 - Seth Flowers
我不确定,但是 OpenXmlPowerTools.dll 可能是针对 v2.0.50727 的 - 请检查您的 C# DLL 是如何构建的?如果它是 .NET 4.0,我曾经遇到过类似的问题 - 您需要改为针对 3.5。请尝试并告诉我结果。 - NSGaga-mostly-inactive
@seth 我需要合并多个Word文档,OpenXmlPowerTools是我能找到的最好的工具。这就是为什么我需要从Web服务运行PowerShell脚本。还有其他建议吗? - sh_kamalh
@NSGaga 我已经构建了OpenXmlPowerTools以针对.Net 4.0。我将尝试使所有内容都适用于.Net 3.5并进行尝试。 - sh_kamalh
1个回答

1

你能试着在PowerShell系统模块路径中安装OpenXmlPowerTools模块吗?

C:\Windows\system32\WindowsPowerShell\v1.0\Modules

我已经将包含 DLL 的 OpenXmlPowerTool 文件夹放置在您指定的文件夹中。代码正在工作,不再抱怨 Merge-OpenXmlDoucment。然而合并后的文档没有生成! - sh_kamalh
这似乎是Merge-OpenXmlDocument cmdlet本身的问题。您的答案值得被标记为答案。 - sh_kamalh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接