/// <summary> /// Starts a powershell script using the specified information. /// </summary> /// <param name="script">The powershell script to run.</param> /// <param name="settings">The information about the script to start.</param> /// <returns>Powershell objects.</returns> public Collection <PSObject> Start(string script, PowershellSettings settings) { if (String.IsNullOrEmpty(script)) { throw new ArgumentNullException("script"); } if (settings == null) { throw new ArgumentNullException("settings"); } //Get Script this.SetWorkingDirectory(settings); _Log.Debug(Verbosity.Normal, String.Format("Executing: {0}", this.AppendArguments(script, settings.Arguments, true))); //Call script = this.AppendArguments(script, settings.Arguments, false); return(this.Invoke(script, settings)); }
/// <summary> /// Starts a powershell script using the specified information. /// </summary> /// <param name="path">The path of the script file to run.</param> /// <param name="settings">The information about the script to start.</param> /// <returns>Powershell objects.</returns> public Collection <PSObject> Start(FilePath path, PowershellSettings settings) { if (path == null) { throw new ArgumentNullException("path"); } if (settings == null) { throw new ArgumentNullException("settings"); } //Get Script this.SetWorkingDirectory(settings); string script = "&\"" + path.MakeAbsolute(settings.WorkingDirectory).FullPath + "\""; _Log.Debug(Verbosity.Normal, String.Format("Executing: {0}", this.AppendArguments(script, settings.Arguments, true))); //Call script = this.AppendArguments(script, settings.Arguments, false); return(this.Invoke(script, settings)); }
/// <summary> /// Starts a powershell script using the specified information. /// </summary> /// <param name="uri">The location of the script file to download and run.</param> /// <param name="path">The temporary path to download the file to.</param> /// <param name="settings">The information about the process to start.</param> /// <returns>Powershell objects.</returns> public Collection <PSObject> Start(Uri uri, FilePath path, PowershellSettings settings) { if (uri == null) { throw new ArgumentNullException("uri"); } if (settings == null) { throw new ArgumentNullException("settings"); } //Get Script this.SetWorkingDirectory(settings); string fullPath = path.MakeAbsolute(settings.WorkingDirectory).FullPath; string script = "&\"" + path.MakeAbsolute(settings.WorkingDirectory).FullPath + "\""; //Download Script WebClient client = new WebClient(); client.DownloadFile(uri, fullPath); _Log.Debug(Verbosity.Normal, String.Format("Executing: {0}", this.AppendArguments(script, settings.Arguments, true))); //Call script = this.AppendArguments(script, settings.Arguments, false); return(this.Invoke(script, settings)); }
/// <summary> /// Sets a value indicating whether security should be set to unrestricted. /// </summary> /// <param name="settings">The powershell settings.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings BypassExecutionPolicy(this PowershellSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } settings.BypassExecutionPolicy = true; return(settings); }
/// <summary> /// Sets a value indicating whether the output of an application is written to its on-screen console. /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="outputToAppConsole">true if output should be written to the app's on-screen console; otherwsie, false. The default is true.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings OutputToAppConsole(this PowershellSettings settings, bool outputToAppConsole = true) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.OutputToAppConsole = outputToAppConsole; return(settings); }
/// <summary> /// Sets the authentication mechanism to use when connecting /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="authenticationMechanism">The authentication mechanism to connect with.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings UseAuthenticationMechanism(this PowershellSettings settings, AuthenticationMechanism authenticationMechanism) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.AuthenticationMechanism = authenticationMechanism; return(settings); }
/// <summary> /// Executes scripts using dot sourcing /// </summary> /// <param name="settings">The powershell settings.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings WithDotSourcing(this PowershellSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.UseDotSourcing = true; return(settings); }
/// <summary> /// Sets the optional timeout for powershell command /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="timeout">The timeout duration</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings SetTimeout(this PowershellSettings settings, int timeout) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.Timeout = timeout; return(settings); }
/// <summary> /// Sets a value indicating whether the output of an application is written to the cake console /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="log">true if output should be written to the cake console; otherwise, false. The default is false.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings SetLogOutput(this PowershellSettings settings, bool log = true) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.LogOutput = log; return(settings); }
/// <summary> /// Sets the working directory for the process to be started. /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="path">The working directory where the powershell command is to be started.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings UseWorkingDirectory(this PowershellSettings settings, DirectoryPath path) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.WorkingDirectory = path; return(settings); }
/// <summary> /// Sets a value indicating whether the output of an application should be formatted as text /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="format">true if output should be written to the cake console; otherwise, false. The default is false.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings SetFormatOutput(this PowershellSettings settings, bool format = true) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.FormatOutput = format; return(settings); }
/// <summary> /// Sets the remote port to connect on. /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="port">The remote port to connext on.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings UsePort(this PowershellSettings settings, int port) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.Port = port; return(settings); }
//Helpers private void SetWorkingDirectory(PowershellSettings settings) { if (String.IsNullOrEmpty(settings.ComputerName)) { DirectoryPath workingDirectory = settings.WorkingDirectory ?? _Environment.WorkingDirectory; settings.WorkingDirectory = workingDirectory.MakeAbsolute(_Environment); } else if (settings.WorkingDirectory == null) { settings.WorkingDirectory = new DirectoryPath("C:/"); } }
/// <summary> /// Gets or sets the credentials to use when connecting /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="password">The password to connect with.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings UsePassword(this PowershellSettings settings, string password) { if (settings == null) { throw new ArgumentNullException("settings"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } settings.Password = password; return(settings); }
/// <summary> /// Gets or sets the credentials to use when connecting /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="username">The username to connect with.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings UseUsername(this PowershellSettings settings, string username) { if (settings == null) { throw new ArgumentNullException("settings"); } if (String.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } settings.Username = username; return(settings); }
/// <summary> /// Sets the computer name to connect to /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="name">The computer name</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings UseComputerName(this PowershellSettings settings, string name) { if (settings == null) { throw new ArgumentNullException("settings"); } if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } settings.ComputerName = name; return(settings); }
/// <summary> /// Adds the specified module to load into the initial state /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="module">The module to load.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings WithModule(this PowershellSettings settings, string module) { if (settings == null) { throw new ArgumentNullException("settings"); } if (String.IsNullOrEmpty(module)) { throw new ArgumentNullException("module"); } if (settings.Modules == null) { settings.Modules = new List <string>(); } settings.Modules.Add(module); return(settings); }
/// <summary> /// Sets the arguments for the powershell command /// </summary> /// <param name="settings">The powershell settings.</param> /// <param name="arguments">The arguments to append.</param> /// <returns>The same <see cref="PowershellSettings"/> instance so that multiple calls can be chained.</returns> public static PowershellSettings WithArguments(this PowershellSettings settings, Action <ProcessArgumentBuilder> arguments) { if (settings == null) { throw new ArgumentNullException("settings"); } if (arguments == null) { throw new ArgumentNullException("arguments"); } if (settings.Arguments == null) { settings.Arguments = new ProcessArgumentBuilder(); } arguments(settings.Arguments); return(settings); }
/// <summary> /// Starts a powershell script using the specified information. /// </summary> /// <param name="uri">The location of the script file to download and run.</param> /// <param name="path">The temporary path to download the file to.</param> /// <param name="settings">The information about the process to start.</param> /// <returns>Powershell objects.</returns> public Collection <PSObject> Start(Uri uri, FilePath path, PowershellSettings settings) { if (uri == null) { throw new ArgumentNullException("uri"); } if (settings == null) { throw new ArgumentNullException("settings"); } //Get Script this.SetWorkingDirectory(settings); string prefix = settings.UseDotSourcing ? ". " : "&"; string fullPath = path.MakeAbsolute(settings.WorkingDirectory).FullPath; string script = prefix + "\"" + fullPath + "\""; //Download Script WebClient client = new WebClient(); client.DownloadFile(uri, fullPath); LogExecutingCommand(settings, script); //Call script = this.AppendArguments(script, settings.Arguments, false); return(this.Invoke(script, settings)); }
private Collection <PSObject> Invoke(string script, PowershellSettings settings) { //Create Runspace Runspace runspace = null; if (String.IsNullOrEmpty(settings.ComputerName)) { //Local runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log, settings.OutputToAppConsole)); } else { //Remote WSManConnectionInfo connection = new WSManConnectionInfo(); connection.ComputerName = settings.ComputerName; if (settings.Port > 0) { connection.Port = settings.Port; } else { connection.Port = 5985; } if (!String.IsNullOrEmpty(settings.Username)) { connection.Credential = new PSCredential(settings.Username, settings.Password.MakeSecure()); } if (settings.Timeout.HasValue) { connection.OperationTimeout = settings.Timeout.Value; connection.OpenTimeout = settings.Timeout.Value; } runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log, settings.OutputToAppConsole), connection); } runspace.Open(); //Create Pipline Collection <PSObject> results = null; using (Pipeline pipeline = runspace.CreatePipeline()) { //Invoke Command if (settings.WorkingDirectory != null) { var path = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", settings.WorkingDirectory.FullPath); pipeline.Commands.AddScript("Set-Location -Path " + path); } if ((settings.Modules != null) && (settings.Modules.Count > 0)) { settings.Modules.ToList().ForEach(m => pipeline.Commands.AddScript("Import-Module " + m)); } pipeline.Commands.AddScript(script); if (settings.FormatOutput) { pipeline.Commands.Add("Out-String"); } results = pipeline.Invoke(); //Log Errors if (pipeline.Error.Count > 0) { while (!pipeline.Error.EndOfPipeline) { PSObject value = (PSObject)pipeline.Error.Read(); if (value != null) { ErrorRecord record = (ErrorRecord)value.BaseObject; if (record != null) { _Log.Error(Verbosity.Normal, record.Exception.Message); } } } } } runspace.Close(); runspace.Dispose(); //Log Results if (settings.LogOutput) { foreach (PSObject res in results) { _Log.Debug(Verbosity.Normal, res.ToString()); } } return(results); }
public static Collection <PSObject> StartPowershellFile(this ICakeContext context, FilePath path, PowershellSettings settings) { return(new PowershellRunner(context.Environment, context.Log).Start(path, settings)); }
public static Collection <PSObject> StartPowershellScript(this ICakeContext context, string script, PowershellSettings settings) { return(new PowershellRunner(context).Start(script, settings)); }
private Collection <PSObject> Invoke(string script, PowershellSettings settings) { //Linux Support if (_Environment.Platform.Family != PlatformFamily.Windows) { var tool = new PwshScriptRunner(_Context.FileSystem, _Context.Environment, _Context.ProcessRunner, _Context.Tools); tool.RunScript(script, settings); return(new Collection <PSObject>()); } //Create Runspace Runspace runspace = null; if (String.IsNullOrEmpty(settings.ComputerName)) { //Local runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log, settings.OutputToAppConsole)); } else { //Remote WSManConnectionInfo connection = new WSManConnectionInfo(); connection.ComputerName = settings.ComputerName; if (settings.Port > 0) { connection.Port = settings.Port; } else { connection.Port = 5985; } if (!String.IsNullOrEmpty(settings.Username)) { connection.Credential = new PSCredential(settings.Username, settings.Password.MakeSecure()); connection.AuthenticationMechanism = settings.AuthenticationMechanism; } if (settings.Timeout.HasValue) { connection.OperationTimeout = settings.Timeout.Value; connection.OpenTimeout = settings.Timeout.Value; } runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log, settings.OutputToAppConsole), connection); } runspace.Open(); //Create Pipline using (Pipeline pipeline = runspace.CreatePipeline()) using (var powershellInstance = PowerShell.Create()) { if (settings.BypassExecutionPolicy) { powershellInstance.Runspace = runspace; powershellInstance.AddScript("Set-ExecutionPolicy Unrestricted"); powershellInstance.Invoke(); } //Invoke Command if (settings.WorkingDirectory != null) { var path = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", settings.WorkingDirectory.FullPath); pipeline.Commands.AddScript("Set-Location -Path " + path); } if ((settings.Modules != null) && (settings.Modules.Count > 0)) { settings.Modules.ToList().ForEach(m => pipeline.Commands.AddScript("Import-Module " + m)); } pipeline.Commands.AddScript(script); if (settings.FormatOutput) { pipeline.Commands.Add("Out-Default"); } //Bind Events pipeline.Output.DataReady += Output_DataReady; pipeline.Error.DataReady += Error_DataReady; pipeline.StateChanged += Pipeline_StateChanged; pipeline.InvokeAsync(); //Wait while (!_complete) { Thread.Sleep(500); } //Handle Exceptions var exceptions = _pipelineResults .Select(result => result.BaseObject) .OfType <Exception>().ToArray(); var errors = _pipelineResults .Select(b => b.BaseObject) .OfType <ErrorRecord>() .Select(er => er.Exception ?? new Exception(er.ErrorDetails.Message)).ToArray(); if (exceptions.Any() || (settings.ExceptionOnScriptError && errors.Any())) { var exceptionString = string.Join(" - ", exceptions.Select(e => e.ToString())); exceptionString += string.Join(" - ", errors.Select(e => e.ToString())); throw new AggregateException($"Failed to Execute Powershell Script: {exceptionString}", exceptions); } } runspace.Close(); runspace.Dispose(); return(_pipelineResults); }
private void LogExecutingCommand(PowershellSettings settings, string script, bool safe = true) { _Log.Debug(Verbosity.Normal, String.Format("Executing: {0}", this.AppendArguments(script, settings.Arguments, safe).EscapeCurleyBrackets())); }
private Collection<PSObject> Invoke(string script, PowershellSettings settings) { //Create Runspace Runspace runspace = null; if (String.IsNullOrEmpty(settings.ComputerName)) { //Local runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log, settings.OutputToAppConsole)); } else { //Remote WSManConnectionInfo connection = new WSManConnectionInfo(); connection.ComputerName = settings.ComputerName; if (settings.Port > 0) { connection.Port = settings.Port; } else { connection.Port = 5985; } if (!String.IsNullOrEmpty(settings.Username)) { connection.Credential = new PSCredential(settings.Username, settings.Password.MakeSecure()); } if (settings.Timeout.HasValue) { connection.OperationTimeout = settings.Timeout.Value; connection.OpenTimeout = settings.Timeout.Value; } runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log, settings.OutputToAppConsole), connection); } runspace.Open(); //Create Pipline using (Pipeline pipeline = runspace.CreatePipeline()) { //Invoke Command if (settings.WorkingDirectory != null) { var path = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", settings.WorkingDirectory.FullPath); pipeline.Commands.AddScript("Set-Location -Path " + path); } if ((settings.Modules != null) && (settings.Modules.Count > 0)) { settings.Modules.ToList().ForEach(m => pipeline.Commands.AddScript("Import-Module " + m)); } pipeline.Commands.AddScript(script); if (settings.FormatOutput) { pipeline.Commands.Add("Out-Default"); } //Bind Events pipeline.Output.DataReady += Output_DataReady; pipeline.Error.DataReady += Error_DataReady; pipeline.StateChanged += Pipeline_StateChanged; pipeline.InvokeAsync(); //Wait while (!_complete) { Thread.Sleep(500); } //Handle Exceptions var exceptions = _pipelineResults.Where(result => result.BaseObject is Exception) .Select(e => e.BaseObject as Exception).ToArray(); if (exceptions.Length > 0) { var exceptionString = string.Join(" - ", exceptions.Select(e => e.ToString())); throw new AggregateException($"Failed to Execute Powershell Script: {exceptionString}", exceptions); } } runspace.Close(); runspace.Dispose(); return _pipelineResults; }
private void LogExecutingCommand(PowershellSettings settings, string script, bool safe = true) { _Log.Debug(Verbosity.Normal, String.Format("Executing: {0}", this.AppendArguments(script, settings.Arguments, safe).Replace("{", "{{").Replace("}", "}}"))); }