更新时间:2023-01-04 17:40:22
运行空间不接受凭据。 您必须使用所需的凭据启动PowerShell。
I could invoke a powershell and call a powershell script file but I'm unable to invoke the powershell with different credentials and then do the below activity.
private static string RunScript(string scriptFile, string servername, string volume, string size,string userID,string userpassword) { // Validate parameters StringBuilder stringBuilder = new StringBuilder(); try { if (string.IsNullOrEmpty(scriptFile)) { throw new ArgumentNullException("scriptFile"); } //if (parameters == null) { throw new ArgumentNullException("parameters"); } RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(scriptFile); CommandParameter Param1 = new CommandParameter("-Server ",servername); CommandParameter Param2 = new CommandParameter("-Volumeletter", volume); CommandParameter Param3 = new CommandParameter("-deltasize", size); scriptCommand.Parameters.Add(Param1); scriptCommand.Parameters.Add(Param2); scriptCommand.Parameters.Add(Param3); pipeline.Commands.Add(scriptCommand); log.Info("scriptCommand " + scriptCommand.ToString()); log.Info("scriptCommandValue Param[command] " + scriptCommand.Parameters[0].Value.ToString()); log.Info("scriptCommandValue Param[password] " + scriptCommand.Parameters[1].Value.ToString()); log.Info("scriptCommandValue Param[usename] " + scriptCommand.Parameters[2].Value.ToString()); Collection<PSObject> psObjects; psObjects = pipeline.Invoke(); foreach (PSObject obj in psObjects) { stringBuilder.AppendLine(obj.ToString()); } // Console.WriteLine(stringBuilder.ToString()); log.Info("output string : " + stringBuilder.ToString()); } } catch (Exception ex) { throw ex; } return stringBuilder.ToString(); }
A runspace does not accept credentials. You must start PowerShell with the credentials you want.