2012-08-22 24 views
0

我是新的PowerShell脚本在C#中。我有一个PowerShell脚本文件ps.ps1和PowerShell settingfile ConsoleSettings.psc1如何调用powershell脚本与C#中的参数configfile#

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -psconsolefile "D:\e\ConsoleSettings.psc1" -noexit -command ". 'D:\e\ps.ps1'" 

运行它,并得到“

获取-RST -SearchRoot'ERD /用户-PasswordNeverExpires:$假 - PasswordNotChangedFor 60 - 启用

我正常工作的结果。

现在,我想要得到这样的结果在C#。我的代码是;

private void button1_Click(object sender, EventArgs e) 
     { 
      RunScript(LoadScript(@"d:\e\ps.ps1")); 
     } 


     private string RunScript(string scriptText) 
     { 
      PSConsoleLoadException x = null; ; 
      RunspaceConfiguration rsconfig = RunspaceConfiguration.Create(@"d:\e\ConsoleSettings.psc1", out x); 
      Runspace runspace = RunspaceFactory.CreateRunspace(rsconfig); 
      runspace.Open(); 
      RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); 
      runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); 
      Pipeline pipeline = runspace.CreatePipeline(); 
      pipeline.Commands.AddScript(scriptText); 

      pipeline.Commands.Add("Get-RST -SearchRoot 'erd/user' -PasswordNeverExpires:$false -PasswordNotChangedFor 60 -enabled");    
Collection<PSObject> results = pipeline.Invoke(); 

      runspace.Close(); 
      StringBuilder stringBuilder = new StringBuilder(); 
      foreach (PSObject obj in results) 
      { 
       stringBuilder.AppendLine(obj.ToString()); 
      } 
      return stringBuilder.ToString(); 
     } 

     private string LoadScript(string filename) 
     { 
      try 
      { 
       using (StreamReader sr = new StreamReader(filename)) 
       { 
        StringBuilder fileContents = new StringBuilder(); 
        string curLine; 
        while ((curLine = sr.ReadLine()) != null) 
        { 
         fileContents.Append(curLine + "\n"); 
        } 
        return fileContents.ToString(); 
       } 
      } 
      catch (Exception e) 
      { 
       string errorText = "The file could not be read:"; 
       errorText += e.Message + "\n"; 
       return errorText; 
      } 

     } 

后来才知​​道有一个错误:术语 “GET-RST -SearchRoot'ERD /用户-PasswordNeverExpires:$假-PasswordNotChangedFor 60 - 启用” 不被识别为cmdlet,函数的名称,脚本文件或可操作程序。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。

如何解决这个问题,还是如何调用与CONFIGFILE PowerShell脚本,参数一样(GET-RST -SearchRoot'ERD /用户-PasswordNeverExpires:$假-PasswordNotChangedFor 60 - 启用)在c#

请帮助我...

+0

'返回File.ReadAllText(文件名)' – SLaks

+0

我不understund清楚,我这样做loadscript函数的返回值,但同样的问题继续下去,我把问题调用步骤“收集结果= pipeline.Invoke( );” –

回答

0

您正在将命令行添加为命令而不是脚本。命令用于像cmdlet或不带参数的函数。您将使用其他方法来添加参数。一个简单的解决方案是再次使用AddScript

pipeline.AddScript("Get-RST -SearchRoot 'erd/user' -PasswordNeverExpires:$false -PasswordNotChangedFor 60 -enabled"); 
+0

嗨,亚当,我像一个脚本添加,但我有同样的问题,同样的错误。 –

相关问题