Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Last active September 16, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctigeek/daf33d634c2cb3d500cd to your computer and use it in GitHub Desktop.
Save ctigeek/daf33d634c2cb3d500cd to your computer and use it in GitHub Desktop.
Run powershell file from c#
using System.Management.Automation;
//....
public static async Task<string> RunPowershellScript(string scriptName, Dictionary<string,string> parameters)
{
using (var ps = PowerShell.Create())
{
var script = string.Format(". \"{0}\" {1}", scriptName, string.Join(" ", parameters.Select(p => "-" + p.Key + " '" + p.Value + "'")));
if (debug)
{
log.Debug("Running the following script:\r\n " + script);
}
ps.AddScript(script);
var task = Task<PSDataCollection<PSObject>>.Factory.FromAsync(ps.BeginInvoke(), ps.EndInvoke);
var objs = await task;
if (ps.Streams.Error.Count > 0)
{
throw new Exception(ps.Streams.Error[0].ToString());
}
else
{
if (objs.Count > 0)
{
var result = objs[0].ToString();
return string.IsNullOrEmpty(result) ? null : result;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment