3

I am trying to run a PowerShell script via C# in a Windows Form.

The problem is that I have two enums, and I can't get them in the code right:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace WindowsFormsApp6
{
    static class Program
    {
        /// <summary>
        /// Der Haupteinstiegspunkt für die Anwendung.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }   *here
}

Just so I understand, do I have to add the following under the static void? (at *here):

 using (PowerShell PowerShellInstance = PowerShell.Create())
 {
 }

Then, do I copy paste it in there?

But of course it's not that easy; I Google'd it, but I don't understand what I have to do to get it working...

Enum RandomFood
{#Add Food here:
Pizza
Quesedias
Lasagne
Pasta
Ravioli
}

Enum Meat
{#Add Food here:
Steak
Beaf
Chicken
Cordonbleu
}

function Food {

Clear-Host
  $Foods =  [Enum]::GetValues([RandomFood]) | Get-Random -Count 6
  $Foods += [Enum]::GetValues([Meat]) | Get-Random -Count 1

$foodsOfWeek = $Foods | Get-Random -Count 7
Write-Host `n "Here is you'r List of Meals for this week :D" `n
foreach ($day in [Enum]::GetValues([DayOfWeek])) {
    ([string]$day).Substring(0, 3) + ': ' + $foodsOfWeek[[DayOfWeek]::$day]
}
}

In the end, I would like to be able to just press on a button on the form, and then have it run the script which outputs it to a textbox.

Is that even possible?

Thanks for any help!

7
  • 2
    Is it not possible for you to convert the PowerShell script to C# code and simply use that instead? If not, check out this post: blogs.msdn.microsoft.com/kebab/2014/04/28/… Commented Jun 12, 2018 at 13:43
  • 2
    I use System.Diagnostics.Process to run Powershell scripts. Save the script and run powershell as process with the script location as parameter. msdn.microsoft.com/de-de/library/… Commented Jun 12, 2018 at 13:48
  • @AndreasHassing well it is but I am a total noob at c#... but thats the plann fot the future... for now i just need it running asap :) Commented Jun 12, 2018 at 14:59
  • @kurdy thanks I will have a loock into that! Commented Jun 12, 2018 at 14:59
  • Then the blog post I linked to will get you there (or @srsedate's answer which looks a lot like what the blog post does, in a condensed format). Commented Jun 12, 2018 at 15:00

1 Answer 1

2

You could place your PowerShell script into a separate file and call it on a bound event.

// When a button is clicked...
private void Button_Click(object sender, EventArgs e)
{
    // Create a PS instance...
    using (PowerShell instance = PowerShell.Create())
    {
        // And using information about my script...
        var scriptPath = "C:\\myScriptFile.ps1";
        var myScript = System.IO.File.ReadAllText(scriptPath);
        instance.AddScript(myScript);
        instance.AddParameter("param1", "The value for param1, which in this case is a string.");

        // Run the script.
        var output = instance.Invoke();

        // If there are any errors, throw them and stop.
        if (instance.Streams.Error.Count > 0)
        {
            throw new System.Exception($"There was an error running the script: {instance.Streams.Error[0]}");
        }

        // Parse the output (which is usually a collection of PSObject items).
        foreach (var item in output)
        {
            Console.WriteLine(item.ToString());
        }
    }
}

In this example, you would probably make better use of the passed in event arguments, and perform some better error handling and output logging, but this should get you down the right path.

Note that running your current script as-is will only declare your Food function, but won't actually run it. Make sure there is a function invocation in your script or C# code.

Sign up to request clarification or add additional context in comments.

5 Comments

Jeah I just add food at the bottom of my ps1 script thanks can you maybe tell me how i can send the output to the textbox from there on? Thanks for the awnser btw:D
Run the debugger, hit a breakpoint, and see what the value of output is. From there, add some logic to act against the items in that collection. You probably want to set the Text property of your text box object.
item.ToString() will have the value that you return from the PowerShell script, if I understand your follow-up question correctly. Take the value returned from that and put it in your textbox. Something along the lines of: myTextBox.Text = item.ToString().
hi so I tryed it as you suggested it in your solution but I get multiple errors the first ont i encounter is on the line with the throw $".... it tels me the type needs something like system.Exception..? did u have the same error? and doesen' the line still need the ;?
@alex Sorry about that, I've updated the original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.