0
votes

I'm running a powershell script file (.ps1) programmatically from my SharePoint code. Here is the source code:

using (new Impersonator("username", "domain", "password"))
{
  using (RunspaceInvoke invoker = new RunspaceInvoke())
  {
    invoker.Invoke("Set-ExecutionPolicy Unrestricted");
  }

  string cmdArg = String.Format(@"C:\Office2Pdf\officetopdf.ps1 {0} {1}", 
    DOWNLOAD_FILE_PATH, UPLOAD_FILE_PATH);

  Runspace runspace = RunspaceFactory.CreateRunspace();
  runspace.ApartmentState = System.Threading.ApartmentState.STA;
  runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
  runspace.Open();

  Pipeline pipeline = runspace.CreatePipeline();
  pipeline.Commands.AddScript(cmdArg);

  pipeline.Commands[0].MergeMyResults(
    PipelineResultTypes.Error, PipelineResultTypes.Output);

  Collection<PSObject> results = pipeline.Invoke();
  var error = pipeline.Error.ReadToEnd();
  runspace.Close();

  if (error.Count >= 1)
  {
    string errors = "";

    foreach (var Error in error)
      errors = errors + " " + Error.ToString();
  }
}

What I am doing is

  1. Downloading a ".docx" file from a SharePoint Document Library
  2. Invoking a powershell script which runs a executable file to convert ".docx" to ".pdf" file
  3. Uploading the ".pdf" back to SharePoint Document Library

The sample code is for the 2nd part. It works perfectly in a Console application, but doesn't work inside SharePoint solution. The error was "object not set to an instance of an object". But there is no way to tell which object it refers to.

Ended up using SharePoint Word Automation Services. Works pretty well. Thanks guys.

1
Is the powershell script very long? If not, you should try putting a try/catch around the variables that you think might be null. Have them rethrow new exceptions with the variable name in the message. - skeletank
On which line the exception is thrown? - Machinegon
Collection<PSObject> results = pipeline.Invoke(); The results object contains the error message - ronma

1 Answers

0
votes

It sounds like it is not seeing the file. What method are you using to get the file?

Is it a network path and the webdav protocol \\yoursite@ssl\davwwwroot\site\library\filename will work but the connection has to be established.

In my experience with powershell I have to keep the session logged on and this works. As soon as that session ends it drops that connection.