SharePoint Pals
 | Sign In
How to execute PowerShell script (ps1 file) from C# code
by Tarun Kumar Chatterjee 31 May 2016
.Net – Technology Specialist
Today  :   17     Total  :    5192

There are two way-out I found out to call the ps1 file from C#:

1. Created a batch file which will have the code to execute the ps1 file & the batch file will be executed by C# code

Batch files Code:

@echo offPowershell.exe -executionpolicy remotesigned -File  <ps1 file path>

C# code to execute the batch file:

 System.Security.SecureString pass = new System.Security.SecureString();
             string strPass = Admin Password";
             foreach (char c in strPass)
 System.Diagnostics.Process.Start(@"Batch File Path","Admin User ID", pass,"Domain Name");

2. Created RunSpace & Pipeline to execute the ps1 file directly from C# code

 private Collection<PSObject> RunPsScript(string psScriptPath)
             string psScript = string.Empty;
             if (File.Exists(psScriptPath))
                 psScript = File.ReadAllText(psScriptPath);
                 throw new FileNotFoundException("Wrong path for the script file");
             RunspaceConfiguration config = RunspaceConfiguration.Create();
             PSSnapInException psEx;
             //add Microsoft SharePoint PowerShell SnapIn
             PSSnapInInfo pssnap = config.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out  psEx);
             //create powershell runspace
             Runspace cmdlet = RunspaceFactory.CreateRunspace(config);
             RunspaceInvoke scriptInvoker = new RunspaceInvoke(cmdlet);
             // set powershell execution policy to unrestricted
             scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
             // create a pipeline and load it with command object
             Pipeline pipeline = cmdlet.CreatePipeline();
                 // Using Get-SPFarm powershell command 
                 // this will format the output
                 Collection<PSObject> output = pipeline.Invoke();
                 // process each object in the output and append to stringbuilder  
                 StringBuilder results = new StringBuilder();
                 foreach (PSObject obj in output)
                 return output;
             catch(Exception ex)
                 return null;

Here is my ps1 file code to delete the list items:

 if ((Get-PSSnapin -Name "Microsoft.SharePoint.PowerShell" ) -eq $null) {
     Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue  
 $rootWeb= Get-Spweb <"Site URL">   
 $listToProcess = $rootWeb.GetList("List URL") 
 $NumberOfItemsToDeleteInBatch = 1000
 if($listToProcess -ne $null)
     $numberOfItemsToRetrieve = $NumberOfItemsToDeleteInBatch;
     $camlQueryString = "<Where><Neq><FieldRef Name='ID'/><Value Type='Counter'>-1</Value></Neq></Where>"
     $viewFields="<FieldRef Name='ID' />"
     $camlQuery = New-Object -TypeName "Microsoft.SharePoint.SPQuery" -ArgumentList @($listToProcess.DefaultView);
     $itemCount = 0;
     $listId = $listToProcess.ID;
     [System.Text.StringBuilder]$batchXml = New-Object "System.Text.StringBuilder";
     $batchXml.Append("<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>");
     $command = [System.String]::Format( "<Method><SetList>{0}</SetList><SetVar Name=`"ID`">{1}</SetVar><SetVar Name=`"Cmd`">Delete</SetVar></Method>", $listId, "{0}" );
     $listItems = $listToProcess.GetItems($camlQuery)
     $camlQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
     foreach ($item in $listItems)
         if($item -ne $null)
             $batchXml.Append([System.String]::Format($command, $item.ID.ToString())) | Out-Null;$itemCount++;
     $rootWeb.ProcessBatchData($batchXml.ToString())   | Out-Null;
     #Write-Host "Item deleted successfully" + $itemCount;
 while ($query.ListItemCollectionPosition -ne $null)
     #Write-Host "Cannot find list: " $listToProcess;
 Stop-SPAssignment -Global -AssignmentCollection $assignmentCollection;
  #Write-Host "Finished";

One issue I found at the time of executing ps1 file script from C# & pipeline.invoke() was throwing error "Cannot invoke this function because the current host does not implement it." But it was deleted the list item successfully.

To resolve the issue I had to comment out Write-Host from ps1 script & execute the C# code, that’s it.

Let’s add one item in the list


As a result of executing the RunPsScript or the code written to execute batch file, the item will be deleted from the list


Happy Coding

Tarun Kumar Chatterjee

blog comments powered by Disqus

SharePoint Pals

SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile


Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community

SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation