Condition:- The Powershell Script file should be available in the machine where it needs to be executed. For example if you want to execute a Powershell script file in System A, then the script file should be there in the local disk of System A.
If you want to execute a Powershell script file in a Remote system, then it must be there in the local disk of the Remote System. If the script file is not there in the Remote System, then you have to copy the script file from the System A(from which you are executing the script in the Remote Sytem using C# code) to the Remote System as done in the following code, but for that the Application account needs to have Admin Right in the Remote System for the Remote Connection.
Download the Sample project here
I have added a class PowerShellExec which contains two public method, one for Remote execution and another for execution in the local system.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.IO;
namespace PowerShellExecution
{
public class PowerShellExec
{
public bool RunPowerShellScript(string scriptFullpath, out string output, out string errors)
{
errors = string.Empty;
try
{
var runspace = RunspaceFactory.CreateRunspace();
return RunPowerShellScriptInternal(scriptFullpath, out output, out errors, runspace);
}
catch (Exception e)
{
errors += "Error occurred while Creating Runspace: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
output = string.Empty;
return false;
throw e;
}
}
public bool RunPowerShellScriptRemote(string scriptFullpath, string computer, string username, string password, out string output, out string errors)
{
errors = string.Empty;
try
{
var filename=Path.GetFileName(scriptFullpath);
var credentials = new PSCredential(username, convertToSecureString(password));
//port – Thanks to the blog post at http://blogs.msdn.com/b/wmi/archive/2009/07/22/new-default-ports-for-ws-management-and-powershell-remoting.aspx
//we know what port numbers PowerShell remoting uses. 5985 if you are not using SSL, and 5986 if you are using SSL
var connectionInfo = new WSManConnectionInfo(false, computer, 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credentials);
var runspace = RunspaceFactory.CreateRunspace(connectionInfo);
var remoteScriptFullpath = "\\\\01hw894947\\D$\\Temp\\" + this.GetType().Module.Name + "\\" + Guid.NewGuid() + "\\";
remoteScriptFullpath = Path.GetFullPath(remoteScriptFullpath);
if(!Directory.Exists(remoteScriptFullpath))
{
Directory.CreateDirectory(remoteScriptFullpath);
}
remoteScriptFullpath += filename;
File.Copy(scriptFullpath, remoteScriptFullpath,true);
return RunPowerShellScriptInternal(remoteScriptFullpath, out output, out errors, runspace);
}
catch (Exception e)
{
errors += "Error occurred while Remote System Connection: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
output = string.Empty;
return false;
throw e;
}
}
private System.Security.SecureString convertToSecureString(string password)
{
System.Security.SecureString secure = new System.Security.SecureString();
try
{
if (!string.IsNullOrEmpty(password))
{
foreach (char c in password)
{
secure.AppendChar(c);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.InnerException);
throw ex;
}
return secure;
}
private bool RunPowerShellScriptInternal(string scriptFullpath, out string output, out string errors, Runspace runspace)
{
bool isExecutionSuccessful = true;
output = string.Empty;
errors = string.Empty;
Collection<PSObject> results = new Collection<PSObject>();
Pipeline pipeline = null;
StringBuilder stringBuilder = new StringBuilder();
try
{
runspace.Open();
pipeline = runspace.CreatePipeline();
var cmd = new Command(scriptFullpath);
pipeline.Commands.Add(cmd);
pipeline.Commands.Add("Out-String");
results = pipeline.Invoke();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
if (pipeline.Error.Count > 0)
{
errors += String.Join(Environment.NewLine, pipeline.Error.ReadToEnd().Select(e => e.ToString()));
isExecutionSuccessful = false;
}
}
catch (Exception e)
{
errors += "Error occurred in PowerShell script: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
isExecutionSuccessful = false;
throw e;
}
finally
{
output = stringBuilder.ToString();
pipeline.Dispose();
runspace.Dispose();
}
return isExecutionSuccessful;
}
}
}
Then I added the following code to my Program.cs file in main method to call the methods of above class.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.IO;
namespace PowerShellExecution
{
class Program
{
static void Main(string[] args)
{
PowerShellExec ps = new PowerShellExec();
var scriptFullpath =@"C:\Users\837853\Desktop\Powershell POC\Script.ps1";
string errors=string.Empty;
string output=string.Empty;
var success = ps.RunPowerShellScript(scriptFullpath, out output, out errors)
if (success)
{
Console.WriteLine("Local Execution Successful.");
Console.WriteLine(output);
}
else
{
Console.WriteLine(errors);
}
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.IO;
namespace PowerShellExecution
{
class Program
{
static void Main(string[] args)
{
PowerShellExec ps = new PowerShellExec();
var scriptFullpath =@"C:\Users\837853\Desktop\Powershell POC\Script.ps1";
var computer = "01hw894947";
var username = @"INDIA\740471";
var password = "Apr@2016";
string errors=string.Empty;
string output=string.Empty;
var success = ps.RunPowerShellScriptRemote(scriptFullpath, computer, username, password, out output, out errors);
if (success)
{
Console.WriteLine("Remote Execution Successful.");
Console.WriteLine(output);
}
else
{
Console.WriteLine(errors);
}
Console.ReadKey();
}
}
}
If you want to execute a Powershell script file in a Remote system, then it must be there in the local disk of the Remote System. If the script file is not there in the Remote System, then you have to copy the script file from the System A(from which you are executing the script in the Remote Sytem using C# code) to the Remote System as done in the following code, but for that the Application account needs to have Admin Right in the Remote System for the Remote Connection.
Download the Sample project here
I have added a class PowerShellExec which contains two public method, one for Remote execution and another for execution in the local system.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.IO;
namespace PowerShellExecution
{
public class PowerShellExec
{
public bool RunPowerShellScript(string scriptFullpath, out string output, out string errors)
{
errors = string.Empty;
try
{
var runspace = RunspaceFactory.CreateRunspace();
return RunPowerShellScriptInternal(scriptFullpath, out output, out errors, runspace);
}
catch (Exception e)
{
errors += "Error occurred while Creating Runspace: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
output = string.Empty;
return false;
throw e;
}
}
public bool RunPowerShellScriptRemote(string scriptFullpath, string computer, string username, string password, out string output, out string errors)
{
errors = string.Empty;
try
{
var filename=Path.GetFileName(scriptFullpath);
var credentials = new PSCredential(username, convertToSecureString(password));
//port – Thanks to the blog post at http://blogs.msdn.com/b/wmi/archive/2009/07/22/new-default-ports-for-ws-management-and-powershell-remoting.aspx
//we know what port numbers PowerShell remoting uses. 5985 if you are not using SSL, and 5986 if you are using SSL
var connectionInfo = new WSManConnectionInfo(false, computer, 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credentials);
var runspace = RunspaceFactory.CreateRunspace(connectionInfo);
var remoteScriptFullpath = "\\\\01hw894947\\D$\\Temp\\" + this.GetType().Module.Name + "\\" + Guid.NewGuid() + "\\";
remoteScriptFullpath = Path.GetFullPath(remoteScriptFullpath);
if(!Directory.Exists(remoteScriptFullpath))
{
Directory.CreateDirectory(remoteScriptFullpath);
}
remoteScriptFullpath += filename;
File.Copy(scriptFullpath, remoteScriptFullpath,true);
return RunPowerShellScriptInternal(remoteScriptFullpath, out output, out errors, runspace);
}
catch (Exception e)
{
errors += "Error occurred while Remote System Connection: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
output = string.Empty;
return false;
throw e;
}
}
private System.Security.SecureString convertToSecureString(string password)
{
System.Security.SecureString secure = new System.Security.SecureString();
try
{
if (!string.IsNullOrEmpty(password))
{
foreach (char c in password)
{
secure.AppendChar(c);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.InnerException);
throw ex;
}
return secure;
}
private bool RunPowerShellScriptInternal(string scriptFullpath, out string output, out string errors, Runspace runspace)
{
bool isExecutionSuccessful = true;
output = string.Empty;
errors = string.Empty;
Collection<PSObject> results = new Collection<PSObject>();
Pipeline pipeline = null;
StringBuilder stringBuilder = new StringBuilder();
try
{
runspace.Open();
pipeline = runspace.CreatePipeline();
var cmd = new Command(scriptFullpath);
pipeline.Commands.Add(cmd);
pipeline.Commands.Add("Out-String");
results = pipeline.Invoke();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
if (pipeline.Error.Count > 0)
{
errors += String.Join(Environment.NewLine, pipeline.Error.ReadToEnd().Select(e => e.ToString()));
isExecutionSuccessful = false;
}
}
catch (Exception e)
{
errors += "Error occurred in PowerShell script: " + e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException;
isExecutionSuccessful = false;
throw e;
}
finally
{
output = stringBuilder.ToString();
pipeline.Dispose();
runspace.Dispose();
}
return isExecutionSuccessful;
}
}
}
Then I added the following code to my Program.cs file in main method to call the methods of above class.
For Execution of PowerShell script file in the local System
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.IO;
namespace PowerShellExecution
{
class Program
{
static void Main(string[] args)
{
PowerShellExec ps = new PowerShellExec();
var scriptFullpath =@"C:\Users\837853\Desktop\Powershell POC\Script.ps1";
string errors=string.Empty;
string output=string.Empty;
var success = ps.RunPowerShellScript(scriptFullpath, out output, out errors)
if (success)
{
Console.WriteLine("Local Execution Successful.");
Console.WriteLine(output);
}
else
{
Console.WriteLine(errors);
}
Console.ReadKey();
}
}
}
For Execution of PowerShell script file in a Remote System
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.IO;
namespace PowerShellExecution
{
class Program
{
static void Main(string[] args)
{
PowerShellExec ps = new PowerShellExec();
var scriptFullpath =@"C:\Users\837853\Desktop\Powershell POC\Script.ps1";
var computer = "01hw894947";
var username = @"INDIA\740471";
var password = "Apr@2016";
string errors=string.Empty;
string output=string.Empty;
var success = ps.RunPowerShellScriptRemote(scriptFullpath, computer, username, password, out output, out errors);
if (success)
{
Console.WriteLine("Remote Execution Successful.");
Console.WriteLine(output);
}
else
{
Console.WriteLine(errors);
}
Console.ReadKey();
}
}
}
References
- http://stackoverflow.com/questions/20195392/to-call-a-powershell-script-file-example-ps1-from-c-sharp
- http://stackoverflow.com/questions/9828569/run-a-remote-powershell-script-on-a-different-remote-server-in-a-c-sharp-runspac
- https://gist.github.com/mdhorda/70c012af0c793938ff1f
- https://com2kid.wordpress.com/2011/09/22/remotely-executing-commands-in-powershell-using-c/
- http://www.codeproject.com/Articles/773685/Enable-Remote-PowerShell-Execution-in-Csharp
- http://jeffmurr.com/blog/?p=142
- http://www.neowin.net/forum/topic/1263570-executing-a-powershell-script-from-c-with-parameters/
- http://stackoverflow.com/questions/11120452/run-powershell-script-from-c-sharp-application
- http://stackoverflow.com/questions/22187464/execute-multiple-line-powershell-script-from-c-sharp
- http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
Dot Net Knowledge: Execute A Powershell Script File In The Local Computer Or In A Remote Computer/Server Using C >>>>> Download Now
ReplyDelete>>>>> Download Full
Dot Net Knowledge: Execute A Powershell Script File In The Local Computer Or In A Remote Computer/Server Using C >>>>> Download LINK
>>>>> Download Now
Dot Net Knowledge: Execute A Powershell Script File In The Local Computer Or In A Remote Computer/Server Using C >>>>> Download Full
>>>>> Download LINK Ir