Powershell command through C# code

前端 未结 1 937
青春惊慌失措
青春惊慌失措 2021-01-14 14:16

I want to add through C# code Powershell command or script (what is correct?) variable declaration with default value stored in C# variable. For example, in Powershell I typ

相关标签:
1条回答
  • 2021-01-14 14:46

    According to this article How to run PowerShell scripts from C#, you will need something like this:

    // create Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();
    // open it
    runspace.Open();
    
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(String.Format("$user = \"{0}\"", userName));
    pipeline.Commands.AddScript("#your main script");
    
    // execute the script
    Collection<psobject> results = pipeline.Invoke();
    // close the runspace
    runspace.Close();
    

    Also see Run Powershell-Script from C# Application question here on Stackoverflow.

    0 讨论(0)
提交回复
热议问题