如何使用configfile调用powershell脚本,c#中的参数

时间:2012-08-22 13:31:53

标签: c# powershell

我是c#中的新PowerShell脚本。我有一个powershell脚本文件ps.ps1和powershell settingfile ConsoleSettings.psc1

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

运行它并获得“

  

Get-RST -SearchRoot'rd / user'-PasswordNeverExpires:$ false   -PasswordNotChangedFor 60 -enabled

我的功能结果正确。

现在,我希望在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 / user'-PasswordNeverExpires:$ false -PasswordNotChangedFor 60 -enabled”不被识别为cmdlet,函数,脚本的名称文件或可操作程序。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。

如何解决这个问题,或如何使用configfile调用powershell脚本,参数如(get-RST -SearchRoot'erd / user'-PasswordNeverExpires:$ false -PasswordNotChangedFor 60 -enabled)in c#

请帮帮我......

1 个答案:

答案 0 :(得分:0)

您将命令行添加为Command而不是脚本。命令适用于cmdlet或没有参数的函数。您将使用其他方法添加参数。一个简单的解决方案就是再次使用AddScript

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