How to execute PowerShell script (ps1 file) from C# code

Tarun Kumar Chatterjee
 
Net – Technology Specialist
May 31, 2016
 
Rate this article
 
Views
42594

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)
             {
                 pass.AppendChar(c);
             }
 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);
             else
                 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);
             cmdlet.Open();
             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();
             try
             { 
                 // Using Get-SPFarm powershell command 
                 pipeline.Commands.AddScript(psScript);
                 pipeline.Commands.AddScript("Out-String");
                 // this will format the output
                 Collection<PSObject> output = pipeline.Invoke();
                 pipeline.Stop();
                 cmdlet.Close();
                 // process each object in the output and append to stringbuilder  
                 StringBuilder results = new StringBuilder();
                 foreach (PSObject obj in output)
                 {
                     results.AppendLine(obj.ToString());
                 }
                 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);
     $camlQuery.Query=$camlQueryString;
     $camlQuery.ViewFields=$viewFields;
     $camlQuery.ViewFieldsOnly=$true
     $camlQuery.RowLimit=$numberOfItemsToRetrieve;
 
 
 do
 {
 
     $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++;
         }
     }
     $batchXml.Append("</Batch>");
     $itemCount;
     $rootWeb.ProcessBatchData($batchXml.ToString())   | Out-Null;
 
     #Write-Host "Item deleted successfully" + $itemCount;
                     
 }
 
 while ($query.ListItemCollectionPosition -ne $null)
     $rootWeb.Dispose();
                 
 }
 else
 {
     #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

clip_image002

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

clip_image004

Happy Coding

Tarun Kumar Chatterjee

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

How to Execute EXE from SharePoint 2013 using Javascript.

Sathish Nadarajan
 
Solution Architect
June 15, 2015
 
Rate this article
 
Views
15375

In the last article, we saw how to execute an EXE by means of Central Admin Setting. But the same thing can also be done using the JavaScript. It has its own limitation. Anyhow, let us know about that. The limitation, let me post at the end.

The Javascript to execute is as follows. It is very simple and straight forward.

 <input type=”button” value=”Launch Notepad” onclick=”LaunchApp” />
 <script>
 function LaunchApp() {
 var ws = new ActiveXObject(‘WScript.Shell’);
 ws.Exec(‘C:\Windows\notepad.exe’);
 }
 < /script>
 

This requires the following Browser settings modifications as well. This is because, as we are using ActiveXObjects.

1. Open the Internet Options from the Tools Menu.

image

2. On the Security Tab, select the relevant Zone. i.e., either the Local intranet, trusted sites etc.,

image

3. Click on the Custom Level.

4. Select the “Initialize and Script ActiveX Controls not marked as safe” as enabled.

image

5. Clear the Cookies and Cache.

6. Refresh the browser and Click on the Link. The ActiveX objects will get initialized properly.

As I said earlier, the limitation is, this method will not execute an EXE which is being stored in the Document Library. This will retrieve only the default EXE’s from the Client Machine. In that scenario, we need to map the Document Library as a Network Folder on the Client’s Machine and then execute this. That involves a lot of training to the end user. Probably in very rare scenario, we can go with this, if there is no other option.

Happy Coding,

Sathish Nadarajan.

Category : JavaScript, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Execute an EXE stored in a Document Library directly in Client’s Machine in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
June 14, 2015
 
Rate this article
 
Views
17244

Recently in our application, I met with some requirement like, there are certain tools (utilities/EXE’s) were there, which were stored on the Document Libraries. When the End User clicks on those links, they are asking for the default SAVE, SAVE AS Options alone. As shown in the figure below.

image

There is no Run Option. i.e., if the user is a frequent user, then the download is happening whenever he clicks on the link. To avoid this, and to make a User friendly approach, on click, directly it should Run. It will ask for your permission. That we cannot avoid. But, the download will not happen frequently.

To achieve, this again, let us go by step by step. In the Previous article, we saw how to upload the EXE files into SharePoint Document Library.

1. Go to Central Administration.

image

2. Go to Manage Web Applications.

image

3. Select the Web Application and Click on General Settings.

image

4. On the Browse file Handling Section, select Permissive. By default, it will be Strict.

5. Click OK and come back.

6. Click on the EXE from your document library.

7. We will get the third option called Run.

image

For the testing purpose, I have created a TrialWindows.exe and uploaded.

 

Happy Coding,

Sathish Nadarajan.

Category : SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment