Last active
September 16, 2016 12:22
-
-
Save ctigeek/daf33d634c2cb3d500cd to your computer and use it in GitHub Desktop.
Run powershell file from c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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