Question:
I have a PowerShell script stored in a file, MergeDocuments.ps1. When I run the script from the Windows PowerShell command prompt it runs fine
.\MergeDocuments.ps1 1.docx 2.docx merge.docx
Calling the script from a Windows console application also runs fine.
When I tried calling the script from an Asp.Net web service, I faced some issues regarding registry access. I used impersonation and gave permission to Network Service account to the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
to solve this problem
Next I faced issue about PowerShell being unable to create objects of type OpenXmlPowerTools.DocumentSource[], so I added the following to my script
1 2 3 |
Add-Type -Path "C:\Users\Administrator\Documents\WindowsPowerShell\Modules\OpenXmlPowerTools\OpenXmlPowerTools.dll" Import-Module OpenXmlPowerTools |
Now the current problem is that I am getting the error “The term ‘Merge-OpenXmlDocument’ is not recognized as the name of a cmdlet, …”
How can I solve that?
PowerShell Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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 Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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(); } |
Answer:
Can you just try to install OpenXmlPowerTools
module in the PowerShell System module path :
1 2 |
C:\Windows\system32\WindowsPowerShell\v1.0\Modules |