Running PowerShell script from .NET

Mark Sanchez 101 Reputation points
2021-09-30T16:07:44.373+00:00

I can open PowerShell (as Administrator) and run the cmdlet here that calls a SQL Job with success:

136746-ps.jpg

I’d like to be able to call this same cmdlet directly (or indirectly via a ps1 file) from a .NET WinForm application by clicking a button. What is the best way to go about doing this? This is not for any distributed app, just something I will run personally using my local admin account.

Windows for business Windows Server User experience PowerShell
Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2021-10-01T08:06:17.963+00:00

    @Mark Sanchez , I make a code example in this link and you could refer to it to call the powershell in c#.

    Example:

       string datetime= textBox1.Text;  
        PowerShell ps = PowerShell.Create();  
        string script = string.Format("(Get-ChildItem d:\\New.txt).CreationTime = '{0}'", datetime);  
        ps.AddScript(script);  
        ps.Invoke();  
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    4 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.