Home > Blockchain >  How can I run a short powershell script in my C# WinForms Application?
How can I run a short powershell script in my C# WinForms Application?

Time:11-01

I've built a monitoring application and one of the many things it will monitor are a few services on a few different servers in our network and I'd like to display the status of these services and whether they are still working or not.

So, lets say I'd want to run this short Powershell script;

Get-Service -ComputerName "DESKTOP" -Name "WinDefend"

And let's say I'd like to run this every 1 minute using the Timer event. Which would look something like this;

private void InitializeTimer()
{
    // Call this procedure when the application starts 
    timer1.Interval = 60000; // 60 seconds
    timer1.Tick  = new EventHandler(timer1_Tick);

    // Enable timer
    timer1.Enabled = true;
}

// Timer tick
private void timer1_Tick(object sender, EventArgs e)
{
    // Powershell script here
}

How would I actually implement this short Powershell script into this example?

My second question would also be, how could I correctly display the data after retreiving it? Could I somehow Write the data to maybe a text box or Label?

Thank you very much for any feedback and/ or help!

CodePudding user response:

If you are trying to execute a single PowerShell command, then maybe the answers to Run PSCmdLets in C# code (Citrix XenDesktop) and How to execute a powershell script using c# and setting execution policy? would do what you want.

I'm doing everything in PowerShell right now, so just easier for me to create a PowerShell script that calls C# that Calls PowerShell. This PowerShell script calls the Run method of the C# class DoPS that invokes Get-Service -ComputerName "." -Name "WinDefend" and then uses WriteLine statements to mimic the expected output of Get-Service:

Add-Type -Language 'CSharp' -TypeDefinition @'
using System;
using System.Management.Automation;
public class DoPS {
    public void Run(){
        //Get-Service -ComputerName "." -Name "WinDefend"
        PowerShell ps = PowerShell.Create();
        ps.AddCommand("Get-Service").AddParameter("ComputerName", ".").AddParameter("Name", "WinDefend");
        Console.WriteLine("Status   Name               DisplayName");
        Console.WriteLine("------   ----               -----------");
        foreach (PSObject result in ps.Invoke()) {
            Console.WriteLine(
                "{0,-9}{1,-19}{2}",
                result.Members["Status"].Value,
                result.Members["Name"].Value,
                result.Members["DisplayName"].Value);
        }
    }
}
'@
$DoPS = [DoPS]::new()
$DoPS.Run()

Which outputs this text:

Status   Name               DisplayName
------   ----               -----------
Running  WinDefend          Microsoft Defender Antivirus Service
  • Related