Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The term ' ' is not recognized as the name of a cmdlet,

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

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

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

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();
}
like image 470
sh_kamalh Avatar asked Nov 13 '22 06:11

sh_kamalh


1 Answers

Can you just try to install OpenXmlPowerTools module in the PowerShell System module path :

C:\Windows\system32\WindowsPowerShell\v1.0\Modules
like image 63
JPBlanc Avatar answered Nov 16 '22 04:11

JPBlanc