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
- Downloading a ".docx" file from a SharePoint Document Library
- Invoking a powershell script which runs a executable file to convert ".docx" to ".pdf" file
- 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.