通过C#代码执行Powershell命令
我想通过C#code Powershell命令或脚本(什么是正确的?)添加变量声明,默认值存储在C#variable中。 例如,在Powershell中,我键入以下行通过C#代码执行Powershell命令,c#,.net,powershell,powershell-2.0,C#,.net,Powershell,Powershell 2.0,我想通过C#code Powershell命令或脚本(什么是正确的?)添加变量声明,默认值存储在C#variable中。 例如,在Powershell中,我键入以下行 $user = 'Admin' 我想在C代码中添加这一行 或 我尝试使用AddCommand(),但它引发异常。我使用PS 2.0。根据本文,您将需要以下内容: // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace();
$user = 'Admin'
我想在C代码中添加这一行
或
我尝试使用AddCommand(),但它引发异常。我使用PS 2.0。根据本文,您将需要以下内容:
// 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();
//创建Powershell运行空间
Runspace Runspace=RunspaceFactory.CreateRunspace();
//打开它
Open();
Pipeline Pipeline=runspace.CreatePipeline();
pipeline.Commands.AddScript(String.Format($user=\“{0}\”,用户名));
pipeline.Commands.AddScript(“您的主脚本”);
//执行脚本
收集结果=pipeline.Invoke();
//关闭运行空间
runspace.Close();
另请参见此处有关Stackoverflow的问题。您不应该改用
AddScript
方法吗?
powershell.AddCommand(String.Format("$user = \"{0}\"", userName));
// 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();