简体   繁体   English

Powershell命令通过C#代码

[英]Powershell command through C# code

I want to add through C# code Powershell command or script (what is correct?) variable declaration with default value stored in C# variable. 我想通过C#代码添加Powershell命令或脚本(什么是正确的?)变量声明,默认值存储在C#变量中。 For example, in Powershell I typing following line 例如,在Powershell中我输入以下行

 $user = 'Admin'

I want to add this line in C# code. 我想在C#代码中添加这一行。

powershell.AddScript(String.Format("$user = \"{0}\"", userName));

or 要么

powershell.AddCommand(String.Format("$user = \"{0}\"", userName));

I try with AddCommand() but it throws exception. 我尝试使用AddCommand()但它抛出异常。 I use PS 2.0. 我用的是PS 2.0。

According to this article How to run PowerShell scripts from C# , you will need something like this: 根据这篇文章如何从C#运行PowerShell脚本 ,你需要这样的东西:

// 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. 另请参阅Stackoverflow上的C#Application问题中的Run Powershell-Script

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM