This article will display an entertaining example how to execute Powershell from C#. We will use Linqpad, available here: Download LinqPad now The code executes a Powershell scripts, then uses different objects in System.Management.Automation for working with Powershell from C#. The Powershell script is executed inside Linqpad, where C# code is pasted. The code itself will animate the active processes on the computer running the Linqpad C# code, executing the Powershell script. The code is listed below. Paste the code into Linqpad. You might want to adjust the Task.Delay and for loop for controlling how quick you want to refresh and how long to run (# iterations).
public class CpuNode { public CpuNode(string name, int percentage){ ProcessName = name; Percentage = percentage; } public string ProcessName { get; set; } public int Percentage { get; set; } } async void Main() { Chart c = new Chart(); Series s = c.Series.Add("ActiveProcesses"); s.ChartType = SeriesChartType.Column; Title title = new Title("Active processes using CPU (%)", Docking.Top, new Font("Verdana", 18), Color.MidnightBlue); c.Titles.Add(title); var ca = new ChartArea(); var ca3D = new ChartArea3DStyle(); ca3D.Enable3D = true; ca.Area3DStyle = ca3D; ca.AxisY.Maximum = 100; ca.AxisY.Minimum = 0; ca.BackColor = Color.AliceBlue; ca.AxisX.Title = "Process name"; ca.AxisY.Title = "CPU Percentage %"; Legend lg = new Legend(); lg.Title = "CPU"; lg.BackColor = Color.AliceBlue; c.Legends.Add(lg); c.ChartAreas.Add(ca); c.Dump(""); string cpuPsScript = @"get-wmiobject Win32_PerfFormattedData_PerfProc_Process| Select-Object -Property Name, PercentProcessorTime | Where-Object { $_.Name -ne '_Total' } | Where-Object { $_.Name -ne 'Idle' } "; using (PowerShell powerShellInstance = PowerShell.Create()){ powerShellInstance.AddScript(cpuPsScript); List<CpuNode> nodes = new List<CpuNode>(); for (int i=0; i<1000; i++){ Collection<PSObject> psOutput = powerShellInstance.Invoke(); s.Points.Clear(); nodes.Clear(); int n = 1; foreach (PSObject outputItem in psOutput){ try { string processName = outputItem.Properties["Name"].Value.ToString(); int processPercentage = int.Parse(outputItem.Properties["PercentProcessorTime"].Value.ToString()); var node = new CpuNode(processName, processPercentage); nodes.Add(node); } //try catch (Exception err){ err.Message.Dump(); } //try-catch } //foreach foreach (var node in nodes.OrderBy(x => x.ProcessName)){ var dt = new DataPoint(n, node.Percentage); if (node.Percentage > 1){ dt.Label = node.ProcessName + " (" + node.Percentage + "%)"; } dt.Color = ColorTranslator.FromHtml("#FF418CF0"); s.Points.Add(dt); n = n + 1; } c.ResumeLayout(); await Task.Delay(250); } //for } } // Define other methods and classes here
The code uses the Powershell cmdlet get-mwiobject and uses the performance counter Win32_PerfFormatttedData_PerfProc_Process We use the PowerShell.Create() method to create the Powershell instance and add a script using the .AddScript method. We then Invoke the Powershell instance, grab hold of the PsObject items and then readily accesses the Properties inside. We build up a Chart object with a chart series, having data points and setting up a nice formatting. When the Chart object is created, we let LinqPad display it for us in a tab pane. Now that was fun, wasn't it? Now go code some more :-)
No comments:
Post a Comment