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.

share|improve this question
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 Mar 13 at 13:14
On which line the exception is thrown? – Machinegon Mar 14 at 15:12
Collection<PSObject> results = pipeline.Invoke(); The results object contains the error message – ronma Mar 15 at 0:37

1 Answer

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.

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.