none
Executing PowerShell command with parameters from C# RRS feed

  • Question

  • Hello, I try to execute some PowerShell commands with parameters from c#.

    This works fine:

    using (PowerShell PowerShellInstance = PowerShell.Create())
    {
       PowerShellInstance.AddScript("param($param1); Get-ChildItem $param1");
       PowerShellInstance.AddParameter("param1", "C:\\");
    
       Collection<PSObject> PSOutput =  PowerShellInstance.Invoke();
    
       foreach (var item in PSOutput)
       {
          if(item != null)
          {
            Console.WriteLine(item.BaseObject.ToString());
          }
       }
    }

    But this does not work:

    using (PowerShell PowerShellInstance = PowerShell.Create())
    {
       PowerShellInstance.AddScript("param($param1); Get-ChildItem $param1");
       PowerShellInstance.AddParameter("param1", "-Path C:\\");
    
       ...
    }

    Can someone help me to correct the last code. I would like to use the "-Path" parameter and later the "-Exclude" parameter like this in PowerShell:

    Get-ChildItem -Path C: -Exclude *.exe


    Thursday, June 13, 2019 2:20 PM

Answers

  • Hi tim-othy555,

    Thank you for posting here.

    For your question, here is a simple way for your reference. You could download the source file from the code project.

    https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by tim-othy555 Friday, June 14, 2019 8:52 AM
    Friday, June 14, 2019 3:16 AM
    Moderator

All replies

  • Hi tim-othy555,

    Thank you for posting here.

    For your question, here is a simple way for your reference. You could download the source file from the code project.

    https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by tim-othy555 Friday, June 14, 2019 8:52 AM
    Friday, June 14, 2019 3:16 AM
    Moderator
  • Hello Wendy,

    thank you for your support.

    Your answer solves my problem.

    Best Regards,

    tim-othy555

    Friday, June 14, 2019 8:52 AM