void InvokePipeline(string code, bool addHistory) { // drop history cache History.Cache = null; // push writer FarUI.PushWriter(new EditorOutputWriter1(Editor)); // invoke try { // history if (addHistory) { code = code.Trim(); if (code.Length > 0 && code[code.Length - 1] != '#' && A.Psf._myLastCommand != code) { History.AddLine(code); A.Psf._myLastCommand = code; } } // invoke command PowerShell = PowerShell.Create(); PowerShell.Runspace = Runspace; PowerShell.Commands .AddScript(code) .AddCommand(A.OutHostCommand); Editor.BeginAsync(); PowerShell.BeginInvoke<PSObject>(null, null, AsyncInvoke, null); } catch (RuntimeException ex) { Far.Api.ShowError(Res.Me, ex); } }
/// <summary> /// Called to start the COM handler. /// </summary> /// <param name="data">Data string passed in from Task Scheduler action.</param> public override void Start(string data) { psInstance = PowerShell.Create(); psInstance.AddScript(data); result = psInstance.BeginInvoke(); psInstance.InvocationStateChanged += PowerShellInstance_InvocationStateChanged; }
public void ExecuteScript(ScriptConfigElement e) { using (_instance = PowerShell.Create()) { _instance.AddScript(File.ReadAllText(e.PathToScript)); PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += outputCollection_DataAdded; _instance.Streams.Progress.DataAdded += Progress_DataAdded; _instance.Streams.Error.DataAdded += Error_DataAdded; _instance.Streams.Verbose.DataAdded += Verbose_DataAdded; _instance.Streams.Debug.DataAdded += Debug_DataAdded; _instance.Streams.Warning.DataAdded += Warning_DataAdded; IAsyncResult result = _instance.BeginInvoke<PSObject, PSObject>(null, outputCollection); while (result.IsCompleted == false) { Thread.Sleep(500); } foreach (PSObject o in outputCollection) { Console.WriteLine(o.GetType()); Console.WriteLine(o); } } }
public void ExecuteCommand(string command, int timeoutSeconds = 30) { if (String.IsNullOrEmpty(command)) { throw new NullReferenceException("The command must not be blank"); } if (timeoutSeconds < 1) { throw new ArgumentOutOfRangeException("The timeout must be greater than 0"); } int timeoutMilliseconds = timeoutSeconds * 1000; _powerShellInstance.Commands.Clear(); try { _powerShellInstance.AddScript(command); // prepare a new collection to store output stream objects PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); //outputCollection.DataAdded += (obj,e) => //{ // PrintPSOutput((PSDataCollection<PSObject>)obj); //}; IAsyncResult result = _powerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); int i = 0; int countSecs = 0; while (result.IsCompleted == false) { if (i > 0) { if (i == timeoutMilliseconds) { _powerShellInstance.Stop(); throw new TimeoutException($"Command exceeded timeout of {timeoutSeconds}s"); } if (i % _counterMilliseconds == 0) { countSecs++; Console.WriteLine($"Command run for {countSecs}s"); } } Thread.Sleep(_statusCheckMilliseconds); i += _statusCheckMilliseconds; } // check the other output streams (for example, the error stream) if (_powerShellInstance.Streams.Error.Count > 0) { foreach (var error in _powerShellInstance.Streams.Error) { if (_verbose) { Console.WriteLine(error.ToString()); } } ReportErrors(_powerShellInstance.Streams.Error.Select(e => e.ToString())); } else { PrintPSOutput(outputCollection); } } catch (Exception ex) { throw new Exception("Error executing command", ex); } }
/// <summary> /// Validates an ARM template. /// </summary> /// <param name="resourceGroupName">The name of the resource group to validate against.</param> /// <param name="templateFilePath">Path to the ARM template file to validate.</param> /// <param name="templateParametersFilePath">Path to the ARM template parameters file to use with validation.</param> /// <returns>True if valid, and false if invalid.</returns> public static bool ValidateTemplate(string resourceGroupName, string templateFilePath, string templateParametersFilePath) { if (!Directory.Exists(_tempArmDir)) { Directory.CreateDirectory(_tempArmDir); } ArmTemplateHelper.LoadArmTemplateParameters(templateParametersFilePath); IEnumerable <string> parameterNames = ArmTemplateHelper.GetParameterNames(templateParametersFilePath); foreach (string parameterName in parameterNames) { ArmTemplateHelper.SetParameterValue( templateParametersFilePath, parameterName, ArmTemplateHelper.GetParameterValue( templateParametersFilePath, parameterName)); } string templateParameterFileName = Path.GetFileName(templateParametersFilePath); string tempParametersFilePath = $@"{_tempArmDir}\{templateParameterFileName}"; ArmTemplateHelper.SaveConfiguration(templateParametersFilePath, tempParametersFilePath); using (PowerShell powerShellInstance = PowerShell.Create()) { powerShellInstance.AddCommand("Test-AzResourceGroupDeployment"); powerShellInstance.AddParameter("-ResourceGroupName", resourceGroupName); powerShellInstance.AddParameter("-TemplateFile", templateFilePath); powerShellInstance.AddParameter("-TemplateParameterFile", tempParametersFilePath); PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); powerShellInstance.Streams.Error.DataAdded += Error_DataAdded; IAsyncResult result = powerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); while (!result.IsCompleted) { Debug.WriteLine("Waiting for pipeline to finish."); Thread.Sleep(1000); } Debug.WriteLine("Execution has stopped. The pipeline state: " + powerShellInstance.InvocationStateInfo.State); string serializedOutput = PSSerializer.Serialize(outputCollection); XNamespace ns = "http://schemas.microsoft.com/powershell/2004/04"; XDocument output = XDocument.Parse(serializedOutput); List <XElement> messageElements = output.Root.Descendants(ns + "S") .Where(x => x.Attribute("N") != null && x.Attribute("N").Value == "Message") .ToList(); foreach (XElement messageElement in messageElements) { Debug.WriteLine($"ERROR: {messageElement.Value}"); } if (messageElements.Count() != 0) { return(false); } if (powerShellInstance.Streams.Error.Count() > 0) { return(false); } return(true); } }
void Start(ScriptBlock scriptBlock, Hashtable parameters) { SessionStateAssemblyEntry windowsBase = new SessionStateAssemblyEntry(typeof(Dispatcher).Assembly.ToString()); SessionStateAssemblyEntry presentationCore = new SessionStateAssemblyEntry(typeof(UIElement).Assembly.ToString()); SessionStateAssemblyEntry presentationFramework = new SessionStateAssemblyEntry(typeof(Control).Assembly.ToString()); initialSessionState.Assemblies.Add(windowsBase); initialSessionState.Assemblies.Add(presentationCore); initialSessionState.Assemblies.Add(presentationFramework); initialSessionState.Assemblies.Add(presentationFramework); runspace = RunspaceFactory.CreateRunspace(this.initialSessionState); runspace.ThreadOptions = PSThreadOptions.ReuseThread; runspace.ApartmentState = ApartmentState.STA; runspace.Open(); powerShellCommand = PowerShell.Create(); powerShellCommand.Runspace = runspace; jobThread = powerShellCommand.AddScript("[Threading.Thread]::CurrentThread").Invoke<Thread>()[0]; powerShellCommand.Streams.Error = this.Error; this.Error.DataAdded += new EventHandler<DataAddedEventArgs>(Error_DataAdded); powerShellCommand.Streams.Warning = this.Warning; this.Warning.DataAdded += new EventHandler<DataAddedEventArgs>(Warning_DataAdded); powerShellCommand.Streams.Verbose = this.Verbose; this.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded); powerShellCommand.Streams.Debug = this.Debug; this.Debug.DataAdded += new EventHandler<DataAddedEventArgs>(Debug_DataAdded); powerShellCommand.Streams.Progress = this.Progress; this.Progress.DataAdded += new EventHandler<DataAddedEventArgs>(Progress_DataAdded); this.Output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded); powerShellCommand.Commands.Clear(); powerShellCommand.Commands.AddScript(scriptBlock.ToString(), false); if (parameters.Count > 0) { powerShellCommand.AddParameters(parameters); } Collection<Visual> output = powerShellCommand.Invoke<Visual>(); if (output.Count == 0) { return; } powerShellCommand.Commands.Clear(); powerShellCommand.Commands.AddCommand("Show-Window").AddArgument(output[0]).AddParameter("OutputWindowFirst"); Object var = powerShellCommand.Runspace.SessionStateProxy.GetVariable("NamedControls"); if (var != null && ((var as Hashtable) != null)) { namedControls = var as Hashtable; } JobDispatcher = Dispatcher.FromThread(jobThread); JobDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(jobDispatcher_UnhandledException); powerShellCommand.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(powerShellCommand_InvocationStateChanged); powerShellCommand.BeginInvoke<Object, PSObject>(null, this.Output); DateTime startTime = DateTime.Now; if (output[0] is FrameworkElement) { while (JobWindow == null) { if ((DateTime.Now - startTime) > TimeSpan.FromSeconds(30)) { this.SetJobState(JobState.Failed); return; } System.Threading.Thread.Sleep(25); } } }
private static ActionResult InvokePowershell(CertificateRequestResult result, string executionPolicy, string scriptFile, Dictionary <string, object> parameters, string scriptContent, PowerShell shell, bool autoConvertBoolean = true, string[] ignoredCommandExceptions = null) { // ensure execution policy will allow the script to run, default to system default, default policy is set in service config object if (!string.IsNullOrEmpty(executionPolicy)) { shell.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", executionPolicy) .AddParameter("Scope", "Process") .AddParameter("Force") .Invoke(); } // add script command to invoke if (scriptFile != null) { shell.AddCommand(scriptFile); } else { shell.AddScript(scriptContent); } // pass the result to the script if present if (result != null) { shell.AddParameter("result", result); } // pass parameters to script if present if (parameters != null) { foreach (var a in parameters) { var val = a.Value; if (autoConvertBoolean) { if (val != null && val?.ToString().ToLower() == "true") { val = true; } else if (val != null && val?.ToString().ToLower() == "false") { val = false; } } shell.AddParameter(a.Key, val); } } var errors = new List <string>(); // accumulate output var output = new StringBuilder(); // capture errors if (ignoredCommandExceptions == null) { ignoredCommandExceptions = new string[] { }; } shell.Streams.Error.DataAdded += (sender, args) => { var error = shell.Streams.Error[args.Index]; var src = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName; var msg = $"{src}: {error}\n{error.InvocationInfo.PositionMessage}"; if (!ignoredCommandExceptions.Contains(error.InvocationInfo.MyCommand?.Name)) { errors.Add(msg); } }; // capture write-* methods (except write-host) // TODO: one of these streams may be causing ssh hang when ssh spawned as part of script.. shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message); shell.Streams.Debug.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message); shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message); var outputData = new PSDataCollection <PSObject>(); outputData.DataAdded += (sender, args) => { // capture all main output var data = outputData[args.Index]?.BaseObject; if (data != null) { output.AppendLine(data.ToString()); } }; try { var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData); var maxWait = 60 * 5; // 5 min timeout var currentWait = 0; var pollSeconds = 5; bool timeoutOccurred = false; while (!timeoutOccurred && !async.AsyncWaitHandle.WaitOne(pollSeconds * 1000, false)) { // poll while async task is still running currentWait += pollSeconds; if (currentWait <= maxWait) { output.AppendLine($"Waiting for powershell to complete..{currentWait}s"); } else { output.AppendLine($"Timeout waiting for powershell to complete ({currentWait}s)"); errors.Add($"Script did not complete in the required time. ({maxWait}s)"); timeoutOccurred = true; } } try { if (async.IsCompleted) { shell.EndInvoke(async); output.AppendLine($"Powershell Task Completed."); } } catch (System.Management.Automation.RuntimeException ex) { errors.Add($"{ex.ErrorRecord} {ex.ErrorRecord.ScriptStackTrace}"); } catch (Exception ex) { errors.Add($"Script invoke failed: {ex}"); } if (errors.Any()) { foreach (var e in errors) { output.AppendLine("Error: " + e); } } return(new ActionResult(output.ToString().TrimEnd('\n'), !errors.Any())); } catch (ParseException ex) { // this should only happen in case of script syntax errors, otherwise // errors would be output via the invoke's error stream output.AppendLine($"{ex.Message}"); return(new ActionResult(output.ToString().TrimEnd('\n'), false)); } }
/// <summary> /// Override inside a safe lock. /// </summary> /// <param name="remoteRunspace">Runspace to override.</param> /// <param name="syncObject">Object to use in synchronization.</param> /// <param name="isRunspacePushed">Set is runspace pushed.</param> internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (_localSyncObject) { _stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } } else { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) { // Don't execute command if pushed runspace is already running one. return; } using (PowerShell powerShell = PowerShell.Create()) { powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; powerShell.RemotePowerShell.HostCallReceived += HandleHostCall; IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection <PSObject> results = new PSDataCollection <PSObject>(); while (!_stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(1000); if (asyncResult.IsCompleted) { results = powerShell.EndInvoke(asyncResult); break; } } if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } } } catch (Exception) { _runspaceRef.Revert(); isRunspacePushed = false; throw; } }
public async Task <ICollection <Disk> > GetDisks() { ps.Commands.Clear(); ps.AddCommand("Get-Disk"); var results = await Task.Factory.FromAsync(ps.BeginInvoke(), r => ps.EndInvoke(r)); var disks = results .Select(x => x.ImmediateBaseObject) .Select(x => ToDisk(this, x)); return(disks.ToList()); }
public static async Task <string> RunScript(CertificateRequestResult result, string scriptFile) { // argument check for script file existance and .ps1 extension var scriptInfo = new FileInfo(scriptFile); if (!scriptInfo.Exists) { throw new ArgumentException($"File '{scriptFile}' does not exist."); } if (scriptInfo.Extension != ".ps1") { throw new ArgumentException($"File '{scriptFile}' is not a powershell script."); } var config = SharedUtils.ServiceConfigManager.GetAppServiceConfig(); try { // create a new runspace to isolate the scripts using (var runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); // set working directory to the script file's directory runspace.SessionStateProxy.Path.SetLocation(scriptInfo.DirectoryName); using (PowerShell shell = PowerShell.Create()) { shell.Runspace = runspace; // ensure execution policy will allow the script to run, default to "Unrestricted", set in service config as "Default" to skip. if (config.PowershellExecutionPolicy != "Default") { shell.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", config.PowershellExecutionPolicy) .AddParameter("Scope", "Process") .AddParameter("Force") .Invoke(); } // add script command to invoke shell.AddCommand(scriptFile); // pass the result to the script shell.AddParameter("result", result); // accumulate output var output = new StringBuilder(); // capture errors shell.Streams.Error.DataAdded += (sender, args) => { var error = shell.Streams.Error[args.Index]; string src = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName; output.AppendLine($"{src}: {error}\n{error.InvocationInfo.PositionMessage}"); }; // capture write-* methods (except write-host) shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message); shell.Streams.Debug.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message); shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message); var outputData = new PSDataCollection <PSObject>(); outputData.DataAdded += (sender, args) => { // capture all main output object data = outputData[args.Index]?.BaseObject; if (data != null) { output.AppendLine(data.ToString()); } }; await Task.Run(() => { try { var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData); shell.EndInvoke(async); } catch (ParseException ex) { // this should only happen in case of script syntax errors, otherwise // errors would be output via the invoke's error stream output.AppendLine($"{ex.Message}"); } }); return(output.ToString().TrimEnd('\n')); } } } catch (Exception ex) { return($"Error - {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); } }
/// <summary> /// Create powershell instance for each Job and run it on Ruspacepool. /// Use Tasks to create threads and collect the results. /// If Force parameter is not used and first Job, perform Error check before Queuing remaining Jobs /// </summary> protected override void ProcessRecord() { try { jobNum++; do { try { //Create a powershell instance for each input object and it will be processed on a seperate thread PowerShell powerShell = PowerShell.Create(); IDictionary psParams = RunspaceMethods.FindParams(proxyFunction, ScriptToRun, commandName, InputObject); //If command supplied doesn't take any input, bail out. //This check can be removed if this cmdlet needs to run 'something' in parallel, but just didn't find a use case yet if (psParams.Count <= 0) { throw new Exception("No Parameters were used on the command, Please verify the command."); } if (jobNum == 1) { LogHelper.LogProgress("Queuing First Job", this, quiet: Quiet.IsPresent); LogHelper.Log(fileVerboseLogTypes, "Paramaters used for the first job:", this, NoFileLogging.IsPresent); foreach (DictionaryEntry param in psParams) { string paramValues = null; if (param.Value is Array) { foreach (var val in param.Value as Array) { paramValues += val?.ToString() + ", "; } } else { paramValues = param.Value?.ToString(); } LogHelper.Log(fileVerboseLogTypes, string.Format("{0} - {1}", param.Key.ToString(), paramValues), this, NoFileLogging.IsPresent); } } if (cmdInfo.CommandType == CommandTypes.ExternalScript) { powerShell.AddScript(((ExternalScriptInfo)cmdInfo).ScriptContents).AddParameters(psParams); } else { powerShell.AddCommand(commandName).AddParameters(psParams); } powerShell.RunspacePool = runspacePool; //Creates the task and the continuation tasks Task <PSDataCollection <PSObject> > task = Task <PSDataCollection <PSObject> > .Factory.FromAsync(powerShell.BeginInvoke(), r => powerShell.EndInvoke(r)); task.ContinueWith(t => { var currentJob = CheckandCreateJob( jobName: InputObject.ToString(), task: t, jobID: jobNum, ps: powerShell); currentJob.IsFaulted = true; currentJob.Exceptions = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); //Continuation tasks may have already created the Job, check before creating it. Job job = CheckandCreateJob( jobName: InputObject.ToString(), task: task, jobID: jobNum, ps: powerShell); if (!jobs.TryAdd(job.ID, job)) { if (jobNum == 1) { //We might retry the Job 1 during Error Check, so ignore the error and replace the first job jobs.TryRemove(jobs.First().Key, out Job removedJob); jobs.TryAdd(job.ID, job); } else { throw new Exception(string.Format("Unable to add job ID: {0}", job.ID)); } } if (!Async.IsPresent && (jobs.Count == BatchSize || (!this.Force.IsPresent && (jobNum == 1)))) { CollectJobs(this, jobs, jobNum, ProgressBarStage, Force, ReturnasJobObject, AppendJobNameToResult, jobNum); } if (Async.IsPresent) { WriteObject(job); } } catch (AggregateException ae) when(jobNum == 1 && ae.InnerExceptions.Where(ie => ie is CommandNotFoundException).Count() > 0) { IEnumerable <Exception> exceptions = ae.InnerExceptions.Where(ie => ie is CommandNotFoundException); List <string> debugStrings = new List <string>(); foreach (Exception exception in exceptions) { CommandInfo commandInfo = RunspaceMethods.GetCommandInfo(((CommandNotFoundException)exception).CommandName); if (commandInfo == null) { throw (CommandNotFoundException)exception; } RunspaceMethods.ModuleDetails moduleDetails = RunspaceMethods.GetModuleDetails(commandInfo, debugStrings); LogHelper.LogDebug(debugStrings, this); LogHelper.Log(fileVerboseLogTypes, exception.Message, this, NoFileLogging); if (moduleDetails.IsFromRemotingModule) { LogHelper.Log(fileVerboseLogTypes, "The command is from a remotePS connection, cannot load local and remote runspaces together", this, NoFileLogging); throw exception; } RunspaceMethods.LoadISSWithModuleDetails(moduleDetails, runspacePool.InitialSessionState); } runspacePool = RunspaceMethods.ResetRunspacePool(1, MaxThreads, runspacePool.InitialSessionState.Clone(), new DummyCustomPSHost()); LogHelper.LogDebug("Resetting Runspace to load the new modules", this); LogHelper.Log(fileVerboseLogTypes, "Retrying first job", this, NoFileLogging); runspacePool.Open(); } } while (!Force.IsPresent && jobNum == 1 && jobs.FirstOrDefault().Value?.IsFaulted == true); if (!Force.IsPresent && (jobs.Values.Where(f => f.IsFaulted == true).Count() / jobNum * 100) > promptOnPercentFaults) { if (!ShouldContinue(string.Format("More than {0}% of the jobs are faulted, Do you want to continue with processing rest of the Inputs?", promptOnPercentFaults), "Most Jobs Faulted")) { throw new Exception("Most jobs faulted"); } } } catch (Exception e) { ErrorRecord error = new ErrorRecord(e, e.GetType().Name, ErrorCategory.InvalidData, this); LogHelper.Log(fileVerboseLogTypes, error.Exception.ToString(), this, NoFileLogging.IsPresent); CleanupObjs(this, proxyFunction, runspacePool, e is PipelineStoppedException); ThrowTerminatingError(error); } }
private void button1_Click(object sender, EventArgs e) { button1.Hide(); using (PowerShell PS = PowerShell.Create()) { string path = Directory.GetCurrentDirectory() + @"\amd64\prog.log"; string machineName = Environment.MachineName; string date = DateTime.Today.ToString("yyyy-MM-dd"); string policyUnRestrict = "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy"; string policyRestrict = "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Restricted; Get-ExecutionPolicy"; //TODO add program list generator that doesnt include all the extra junk /*string programList = @"Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Se * lect - Object DisplayName, DisplayVersion, Publisher, InstallDate | Format - Table –AutoSize > C:\Users\administrator\Deskto * p\InstalledProgramsList.txt";*/ string DIR = "cd amd64"; string scan = String.Format(@"./scanstate {0}\\{1}_{2} /localonly /c /ue:* /i:MigUser.xml /i:MigApp.xml /i:MigApp.xml /i:MigDocs.xml /i:MigDocs.xml /v:13 /vsc /progress:prog.log /listfiles:filelist.txt" , store, machineName, date); foreach (var item in checkedListBox1.CheckedItems) { scan += @" /ui:TMCCADMN\" + item; } PS.AddScript(policyUnRestrict); //allows scripts to be run in powershell PS.AddScript(DIR); // move to the directory where the usmt files are stored PS.AddScript(scan); // runs the scan command with provided inputs PS.AddScript(policyRestrict); // restrics powershell again //PSDataCollection<VerboseRecord> records = new PSDataCollection<VerboseRecord>(); //IAsyncResult result = PS.BeginInvoke<PSObject, VerboseRecord>(null, records); // async will allow IAsyncResult result = PS.BeginInvoke(); //checks to see if the powershell script is complete //on completion brings button back and prints log info //TODO add streaming output from prog.log and a progress bar this is a temporary solution while (result.IsCompleted == false) { //var stream = PS.Streams.Verbose; richTextBox1.Text = "migrating."; Application.DoEvents(); Thread.Sleep(500); richTextBox1.Text = "migrating.."; Application.DoEvents(); Thread.Sleep(500); richTextBox1.Text = "migrating..."; Application.DoEvents(); Thread.Sleep(500); Application.DoEvents(); richTextBox1.Text = "migrating...."; Application.DoEvents(); } if (result.IsCompleted == true) { richTextBox1.Text = File.ReadAllText(path); button1.Show(); } } }
private void runTaskButton_Click(object sender, RoutedEventArgs e) { Tasks.Task task; string taskName = tasksBox.Text; switch (taskName) { case "Benchmark": try { task = new BenchmarkTask(labelBox.Text, productBox.Text, parametersBox.Text, int.Parse(loopsBox.Text), ComputerWindow.SelectedComputers(), parseOSList); } catch (FormatException) { MessageBox.Show("ERROR", "Loops is not a number!"); return; } break; case "Boot": task = new BootTask(ComputerWindow.SelectedComputers(), parseOSList); break; case "Reboot": task = new RebootTask(ComputerWindow.SelectedComputers(), parseOSList); break; case "Shutdown": task = new ShutdownTask(ComputerWindow.SelectedComputers(), parseOSList); break; case "Exec": task = new ExecTask(commandTextBox.Text, ComputerWindow.SelectedComputers(), parseOSList); break; case "Winupdate": task = new WinUpdateTask(ComputerWindow.SelectedComputers(), parseOSList); break; case "Update": task = new UpdateTask(ComputerWindow.SelectedComputers(), parseOSList); break; case "Valeta/Dandia": try { task = new BatTask(zipBox.Text, outputPathcBox.Text, int.Parse(countBox.Text), modeBox.Text, (BatTask.BatType)batTypeBox.SelectedIndex, nocopyBox.IsChecked.Value, ComputerWindow.SelectedComputers(), parseOSList); } catch (FormatException) { MessageBox.Show("ERROR", "Test count is not a number!"); return; } break; default: return; } List <Tuple <string, object> > parameters = task.GetJackParameters(); PowerShell psinstance = PowerShell.Create(); psinstance.Streams.Verbose.DataAdded += jackInformationEventHandler; psinstance.Streams.Progress.DataAdded += jackProgressEventHandler; psinstance.Streams.Debug.DataAdded += jackDebugEventHandler; psinstance.Streams.Error.DataAdded += jackErrorEventHandler; //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted Process"); psinstance.AddCommand("Set-ExecutionPolicy"); psinstance.AddParameter("-ExecutionPolicy", "Bypass"); psinstance.AddCommand(SCRIPT_PATH); foreach (var param in parameters) { psinstance.AddParameter(param.Item1, param.Item2); } var results = psinstance.BeginInvoke(); /*foreach (PSObject result in results) * { * AppendOutputText(result.ToString()); * Console.WriteLine(result.ToString()); * }*/ ListBoxItem item = new ListBoxItem(); item.Content = task.ToString(); taskHistoryBox.Items.Add(task); }
/// <summary> /// This method invokes Install-WindowsFeature PowerShell cmdlet to install a specific feature. /// </summary> async public Task <object> AddWindowsFeature(string featureName) { object installStatus = string.Empty; //' Create PowerShell instance using (PowerShell psInstance = PowerShell.Create()) { //' Add command and parameter to PowerShell instance psInstance.AddCommand("Install-WindowsFeature"); psInstance.AddParameter("Name", featureName); // Construct collection to hold pipeline stream objects PSDataCollection <PSObject> streamCollection = new PSDataCollection <PSObject>(); // Invoke execution on the pipeline try { PSDataCollection <PSObject> tResult = await Task.Factory.FromAsync(psInstance.BeginInvoke <PSObject, PSObject>(null, streamCollection), pResult => psInstance.EndInvoke(pResult)); foreach (PSObject psObject in streamCollection) { installStatus = psObject.Members["ExitCode"].Value; } } catch (Exception ex) { MessageBox.Show(String.Format("{0}", ex.Message)); } } return(installStatus); }
private void Connect() { try { connection.On <string, string>("returnPS", (s1, s2) => { lock (_locker) { TimeSpan timeout = new TimeSpan(0, 5, 0); //default timeout = 5min DateTime dStart = DateTime.Now; TimeSpan dDuration = DateTime.Now - dStart; try { using (PowerShell PowerShellInstance = PowerShell.Create()) { //Console.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1); Trace.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1); try { PowerShellInstance.AddScript(s1); PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); outputCollection.DataAdding += OutputCollection_DataAdding;; //PowerShellInstance.Streams.Error.DataAdding += ConsoleError; IAsyncResult async = PowerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); while (async.IsCompleted == false || dDuration > timeout) { //Thread.Sleep(200); dDuration = DateTime.Now - dStart; if (tReInit.Interval > 5000) { tReInit.Interval = 5000; } } Console.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1); } catch (Exception ex) { Console.WriteLine("There was an error: {0}", ex.Message); } } } catch (Exception ex) { Console.WriteLine("ERROR: " + ex.Message); } } //Program.MinimizeFootprint(); }); //New 0.9.0.6 connection.On <string, string>("returnPSAsync", (s1, s2) => { if ((DateTime.Now - tLastPSAsync).TotalSeconds >= 2) { lock (_locker) { //Trace.WriteLine(DateTime.Now.ToString() + "\t run PS async... " + s1); tLastPSAsync = DateTime.Now; var tSWScan = Task.Run(() => { //using (PowerShell PowerShellInstance = PowerShell.Create()) //{ // try // { // PowerShellInstance.AddScript(s1); // var PSResult = PowerShellInstance.Invoke(); // if (PSResult.Count() > 0) // { // string sResult = PSResult.Last().BaseObject.ToString(); // if (!string.IsNullOrEmpty(sResult)) //Do not return empty results // { // if (sResult != sScriptResult) // { // sScriptResult = sResult; // Random rnd = new Random(); // tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit // } // } // } // } // catch (Exception ex) // { // Console.WriteLine("There was an error: {0}", ex.Message); // } //} //Program.MinimizeFootprint(); }); } } }); connection.On <string>("init", (s1) => { try { Trace.Write(DateTime.Now.ToString() + "\t Agent init... "); connection.SendAsync("Init", Hostname).ContinueWith(task1 => { }); Trace.WriteLine(" done."); } catch { } try { foreach (string sGroup in Groups.Split(';')) { connection.SendAsync("JoinGroup", sGroup).ContinueWith(task1 => { }); } //Program.MinimizeFootprint(); } catch { } }); connection.On <string>("reinit", (s1) => { try { Random rnd = new Random(); tReInit.Interval = rnd.Next(200, StatusDelay); //wait max 5s to ReInit } catch { } }); connection.On <string>("status", (s1) => { try { lock (_locker) //prevent parallel status { //Trace.Write(DateTime.Now.ToString() + "\t send status..."); string sResult = "{}"; var host = Dns.GetHostEntry(Dns.GetHostName()); JObject jStatus = new JObject(); jStatus.Add("Hostname", Environment.MachineName); jStatus.Add("id", Environment.MachineName); jStatus.Add("Internal IP", host.AddressList.FirstOrDefault(t => t.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString()); jStatus.Add("Last Reboot", dLastStartup); jStatus.Add("Reboot Pending", false); jStatus.Add("Users Online", true); jStatus.Add("OS", System.Runtime.InteropServices.RuntimeInformation.OSDescription.Split('#')[0]); // Environment.OSVersion.ToString()); jStatus.Add("Version", Environment.OSVersion.Version.ToString()); jStatus.Add("Arch", System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString()); // Environment.Is64BitProcess ? "64-bit" : "???"); jStatus.Add("Lang", Thread.CurrentThread.CurrentCulture.LCID.ToString()); jStatus.Add("User", Environment.UserName); jStatus.Add("ScriptResult", sScriptResult); jStatus.Add("Groups", Groups); sResult = jStatus.ToString(); //using (PowerShell PowerShellInstance = PowerShell.Create()) //{ // try // { // PowerShellInstance.AddScript(Properties.Settings.Default.PSStatus); // var PSResult = PowerShellInstance.Invoke(); // if (PSResult.Count() > 0) // { // sResult = PSResult.Last().BaseObject.ToString(); // sResult = sResult.Replace(Environment.MachineName, Hostname); // JObject jRes = JObject.Parse(sResult); // jRes.Add("ScriptResult", sScriptResult); // jRes.Add("Groups", Properties.Settings.Default.Groups); // sResult = jRes.ToString(); // } // } // catch (Exception ex) // { // Console.WriteLine(" There was an error: {0}", ex.Message); // } //} //connection.InvokeAsync("Status", new object[] { Hostname, sResult }).ContinueWith(task1 => //{ //}); connection.InvokeAsync("Status", Hostname, sResult).Wait(1000); Trace.WriteLine(" done."); //Program.MinimizeFootprint(); } } catch (Exception ex) { Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message); } }); connection.On <string>("version", (s1) => { try { lock (_locker) { Trace.Write(DateTime.Now.ToString() + "\t Get Version... "); //Get File-Version sScriptResult = (FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location)).FileVersion.ToString(); Trace.WriteLine(sScriptResult); Random rnd = new Random(); tReInit.Interval = rnd.Next(200, StatusDelay); //wait max 5s to ReInit } } catch (Exception ex) { Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message); } }); connection.On <string>("wol", (s1) => { try { if (!string.IsNullOrEmpty(s1)) { foreach (string sMAC in s1.Split(';')) { try { WOL.WakeUp(sMAC); //Send Broadcast //Send to local Gateway foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces()) { if (f.OperationalStatus == OperationalStatus.Up) { foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses) { //Only use IPv4 if (d.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { WOL.WakeUp(d.Address, 9, sMAC); } } } } } catch { } } } } catch { } }); connection.On <string>("setinstance", (s1) => { Trace.WriteLine(DateTime.Now.ToString() + "\t Set instance: " + s1); try { lock (_locker) { } //if (!string.IsNullOrEmpty(s1)) //{ // string sConfig = Assembly.GetExecutingAssembly().Location + ".config"; // XmlDocument doc = new XmlDocument(); // doc.Load(sConfig); // doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Instance']/value").InnerText = s1; // doc.Save(sConfig); // RestartService(); // //Update Advanced Installer Persistent Properties // RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true); // if (myKey != null) // { // myKey.SetValue("INSTANCE", s1.Trim(), RegistryValueKind.String); // myKey.Close(); // } //} } catch { } }); connection.On <string>("setendpoint", (s1) => { Trace.WriteLine(DateTime.Now.ToString() + "\t Set Endpoint: " + s1); try { lock (_locker) { } //if (!string.IsNullOrEmpty(s1)) //{ // if (s1.StartsWith("https://")) // { // string sConfig = Assembly.GetExecutingAssembly().Location + ".config"; // XmlDocument doc = new XmlDocument(); // doc.Load(sConfig); // doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Endpoint']/value").InnerText = s1; // doc.Save(sConfig); // RestartService(); // //Update Advanced Installer Persistent Properties // RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true); // if (myKey != null) // { // myKey.SetValue("ENDPOINT", s1.Trim(), RegistryValueKind.String); // myKey.Close(); // } // } //} } catch { } }); connection.On <string>("setgroups", (s1) => { Trace.WriteLine(DateTime.Now.ToString() + "\t Set Groups: " + s1); try { lock (_locker) { } //if (!string.IsNullOrEmpty(s1)) //{ // string sConfig = Assembly.GetExecutingAssembly().Location + ".config"; // XmlDocument doc = new XmlDocument(); // doc.Load(sConfig); // doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Groups']/value").InnerText = s1; // doc.Save(sConfig); // RestartService(); // //Update Advanced Installer Persistent Properties // RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true); // if (myKey != null) // { // myKey.SetValue("GROUPS", s1.Trim(), RegistryValueKind.String); // myKey.Close(); // } //} } catch { } }); connection.On <string>("getgroups", (s1) => { try { if (!string.IsNullOrEmpty(s1)) { sScriptResult = Groups; Random rnd = new Random(); tReInit.Interval = rnd.Next(200, StatusDelay); //wait max 5s to ReInit } } catch { } }); connection.On <string>("restartservice", (s1) => { try { //RestartService(); sScriptResult = "restart Agent..."; } catch { } }); connection.On <string>("rzinstall", (s1) => { //RZInst(s1); }); connection.On <string>("rzupdate", (s1) => { //var tSWScan = Task.Run(() => //{ // try // { // sScriptResult = "Detecting RZ updates..."; // Random rnd = new Random(); // tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit // RZUpdater oUpdate = new RZUpdater(); // RZScan oScan = new RZScan(false, false); // oScan.GetSWRepository().Wait(30000); // oScan.SWScan().Wait(30000); // oScan.CheckUpdates(null).Wait(30000); // if (string.IsNullOrEmpty(s1)) // { // sScriptResult = oScan.NewSoftwareVersions.Count.ToString() + " RZ updates found"; // rnd = new Random(); // tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit // } // List<string> lSW = new List<string>(); // foreach (var oSW in oScan.NewSoftwareVersions) // { // if (string.IsNullOrEmpty(s1) || s1 == "HUB") // { // RZInst(oSW.Shortname); // } // else // { // var SWList = s1.Split(';'); // if (SWList.Contains(oSW.Shortname)) // RZInst(oSW.Shortname); // } // } // } // catch { } //}); }); connection.On <string>("rzscan", (s1) => { //var tSWScan = Task.Run(() => //{ // try // { // sScriptResult = "Detecting updates..."; // Random rnd = new Random(); // tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit // RZUpdater oUpdate = new RZUpdater(); // RZScan oScan = new RZScan(false, false); // oScan.GetSWRepository().Wait(30000); // oScan.SWScan().Wait(30000); // oScan.CheckUpdates(null).Wait(30000); // List<string> lSW = new List<string>(); // foreach (var SW in oScan.NewSoftwareVersions) // { // lSW.Add(SW.Shortname + " " + SW.ProductVersion + " (old:" + SW.MSIProductID + ")"); // } // sScriptResult = JsonConvert.SerializeObject(lSW); // rnd = new Random(); // tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit // } // catch { } //}); }); connection.On <string>("inject", (s1) => { //var tSWScan = Task.Run(() => //{ // try // { // sScriptResult = "Inject external code..."; // try // { // ManagedInjection.Inject(s1); // sScriptResult = "External code executed."; // } // catch (Exception ex) // { // sScriptResult = "Injection error:" + ex.Message; // } // } // catch { } //}); }); connection.On <string, string>("userprocess", (cmd, arg) => { //var tSWScan = Task.Run(() => //{ // if (string.IsNullOrEmpty(cmd)) // { // cmd = Assembly.GetExecutingAssembly().Location; // arg = Environment.MachineName + ":" + "%USERNAME%"; // } // try // { // if (string.IsNullOrEmpty(arg)) // { // ProcessExtensions.StartProcessAsCurrentUser(cmd, null, null, false); // } // else // { // ProcessExtensions.StartProcessAsCurrentUser(null, cmd + " " + arg, null, false); // } // } // catch (Exception ex) // { // Console.WriteLine(ex.Message); // } //}); }); //connection.InvokeCoreAsync("Init", new object[] { Hostname }).Wait(); connection.InvokeAsync("Init", Hostname).ContinueWith(task1 => { try { if (task1.IsFaulted) { Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException()); } else { try { foreach (string sGroup in Groups.Split(';')) { connection.InvokeAsync("JoinGroup", sGroup).ContinueWith(task2 => { }); } //Program.MinimizeFootprint(); } catch { } } } catch { } }); } catch (Exception ex) { Console.WriteLine("There was an error: {0}", ex.Message); } }
public void Run() { var start = DateTime.Now; try { //Ensure we have WebAdministration setup var init = InitialSessionState.CreateDefault(); init.ImportPSModule(new[] { "WebAdministration" }); //We'll need a custom UI because the WebAdmin Cmdlets have issues with killing the Streams events var host = new SIFLessPSHost(m_UI); m_Runspace = RunspaceFactory.CreateRunspace(host, init); m_PSInst = PowerShell.Create(RunspaceMode.NewRunspace); m_PSInst.Runspace = m_Runspace; m_Runspace.Open(); //Attach an event for state changes m_PSInst.InvocationStateChanged += Powershell_InvocationStateChanged; //Our command is the file var scriptCommand = new Command(m_FileName); //Add parameters to the command foreach (var checkedItem in parameterCheckBoxList.CheckedItems) { var sifParam = checkedItem as PSParameter; scriptCommand.Parameters.Add(new CommandParameter(sifParam.Name, true)); } m_PSInst.Commands.AddCommand(scriptCommand); //Wire up our events m_UI.ErrorReceived += AddError; m_UI.WarningReceived += AddWarning; m_UI.InfoReceived += AddInfo; m_UI.DebugReceived += AddDebug; m_UI.VerboseReceived += AddVerbose; m_UI.ProgressReceived += AddProgress; // Invoke the pipeline asynchronously. m_AsyncResult = m_PSInst.BeginInvoke(); //Let's keep an eye on this while it runs while (!m_AsyncResult.IsCompleted) { Thread.Sleep(100); Application.DoEvents(); } toolStripStatusLabel1.Text = $"Finished in {DateTime.Now.Subtract(start).ToReadableString()}"; MessageBox.Show("Done processing"); } catch (Exception ex) { MessageBox.Show($"Error Running Script: {ex.Message}", "Whoops?", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { m_PSInst.Dispose(); } }
/// <summary> /// This is the primary method for executing powershell scripts /// </summary> /// <param name="script"></param> /// <param name="args"></param>(optional) /// <returns>ICollection<PSObject></returns> public ICollection<PSObject> executeScript(string script, IDictionary<string, object> args = null) { try { // create runspace if it is null if (_runspace == null) { _runspace = createRunspace(); } // The PowerShell class implements a Factory Pattern, offering a Create() method that returns a new PowerShell object _ps = PowerShell.Create(); // assign the runspace to the Powershell object _ps.Runspace = _runspace; // create a Command object, initializing it with the script path Command psCommand = new Command(script); // if the args Dictionary is not null, add them to the Command.Parameters collection if (args != null) { foreach (var arg in args) { psCommand.Parameters.Add(arg.Key, arg.Value); } } // add the psCommands object to the Commands property of our PowerShell object _ps.Commands.Commands.Add(psCommand); // Invoke PowerShell asynchronously var asyncResult = _ps.BeginInvoke(); // Could perform other tasks here while waiting for script to complete, if needed // this is analogous to the "await" keyword in an async method asyncResult.AsyncWaitHandle.WaitOne(); // get the result from PowerShell execution var result = _ps.EndInvoke(asyncResult); // release the resources used by the WaitHandle asyncResult.AsyncWaitHandle.Close(); // return the collection of PSObjects return result; } catch (Exception ex) { Debug.WriteLine(ex); return null; } }
/// <summary> /// Wraps command execution into system process call. /// </summary> /// <returns></returns> /// <exception cref="Exception"></exception> public RepeatStatus Execute(StepContribution contribution, ChunkContext chunkContext) { if (Logger.IsTraceEnabled) { Logger.Trace("*** Executing PowerShell Script File: {0}", ScriptResource.GetFullPath()); } //=> PowerShell will throw an error if we do not Suppress ambient transaction... // see https://msdn.microsoft.com/en-us/library/system.transactions.transaction.current(v=vs.110).aspx#NotExistJustToMakeTheAElementVisible using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { //=> Runspace configuration information includes the assemblies, commands, format and type files, // providers, and scripts that are available within the runspace. RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); //Creates a single runspace that uses the default host and runspace configuration using (Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { //=> When this runspace is opened, the default host and runspace configuration // that are defined by Windows PowerShell will be used. runSpace.Open(); //=> Set Variables so they are available to user script... if (Variables != null && Variables.Any()) { foreach (KeyValuePair <string, object> variable in Variables) { runSpace.SessionStateProxy.SetVariable(variable.Key, variable.Value); } } //=> this is exit status variables to be tested on exit from power shell script... // it is defined in PwerShell global scope...and must be set by scipt writer on exit... runSpace.SessionStateProxy.SetVariable("ScriptExitStatus", _scriptExitStatus); //=> Allows the execution of commands from a CLR //RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace); //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); using (PowerShell psInstance = PowerShell.Create()) { try { // prepare a new collection to store output stream objects PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); outputCollection.DataAdded += AllStreams_DataAdded; psInstance.Streams.Error.DataAdded += AllStreams_DataAdded; psInstance.Streams.Verbose.DataAdded += AllStreams_DataAdded; psInstance.Streams.Warning.DataAdded += AllStreams_DataAdded; psInstance.Streams.Debug.DataAdded += AllStreams_DataAdded; psInstance.Runspace = runSpace; //=> This tasklet should be in the same dll as ExitStatus, i.e. Summer.Batch.Core.dll // we need to get the path to loaded Summer.Batch.Core.dll so we can load it in PowerShell var assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; //=> need to load Summer.Batch.Core into runspace so we can reference ExitStatus psInstance.AddScript("[System.Reflection.Assembly]::LoadFrom(\"" + assemblyLocation + "\")").AddStatement(); //=> add user command and its parameters... psInstance.AddCommand(ScriptResource.GetFullPath()); if (Parameters != null && Parameters.Any()) { foreach (KeyValuePair <string, object> variable in Parameters) { psInstance.AddParameter(variable.Key, variable.Value); } } //=> Invoke Asynchronously... IAsyncResult asyncResult = psInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); // do something else until execution has completed. long t0 = DateTime.Now.Ticks; while (!asyncResult.IsCompleted) { //=> take a nap and let script do its job... Thread.Sleep(new TimeSpan(_checkInterval)); //=> to check if job was told to stop... CheckStoppingState(chunkContext); //=> lets make sure we did not exceed alloted time... long timeFromT0 = (long)(new TimeSpan(DateTime.Now.Ticks - t0)).TotalMilliseconds; if (timeFromT0 > _timeout) { //=> Stop PowerShell... psInstance.Stop(); //=> behave based on TimeoutBehaviorOption if (_timeoutBehavior.Equals(TimeoutBehaviorOption.SetExitStatusToFailed)) { contribution.ExitStatus = ExitStatus.Failed; break; } else if (_timeoutBehavior.Equals(TimeoutBehaviorOption.ThrowException)) { //=> lets dump what we got before throwing an error... LogStreams(); throw new FatalStepExecutionException("Execution of PowerShell script exceeded allotted time.", null); } } else if (_execution.TerminateOnly) { //=> Stop PowerShell... psInstance.Stop(); //=> lets dump what we got before throwing an error... LogStreams(); throw new JobInterruptedException( string.Format("Job interrupted while executing PowerShell script '{0}'", ScriptResource.GetFilename())); } else if (_stopped) { psInstance.Stop(); contribution.ExitStatus = ExitStatus.Stopped; break; } } // end while scope //=> Wait to the end of execution... //psInstance.EndInvoke(_asyncResult); //NOTE: asyncResult.IsCompleted will be set to true if PowerShell.Stop was called or // PowerShell completed its work //=> if status not yet set (script completed)...handle completion... if (contribution.ExitStatus.IsRunning()) { //=> script needs to set exit code...if exit code not set we assume 0 var lastExitCode = (int)runSpace.SessionStateProxy.PSVariable.GetValue("LastExitCode", 0); _scriptExitStatus = runSpace.SessionStateProxy.GetVariable("ScriptExitStatus") as ExitStatus; //=> set exit status... if (_scriptExitStatus != null && !_scriptExitStatus.IsRunning()) { if (Logger.IsTraceEnabled) { Logger.Trace("***> ScriptExitStatus returned by script => {0}", _scriptExitStatus); } contribution.ExitStatus = _scriptExitStatus; } else //=> let user decide on ExitStatus { if (Logger.IsTraceEnabled) { if (_scriptExitStatus == null) { Logger.Trace("***> ScriptExitStatus is null. Using PowerShellExitCodeMapper to determine ExitStatus."); } else if (_scriptExitStatus.IsRunning()) { Logger.Trace("***> ScriptExitStatus is EXECUTING or UNKNOWN. Using PowerShellExitCodeMapper to determine ExitStatus."); } } if (PowerShellExitCodeMapper != null) { //=> determine exit status using User Provided PowerShellExitCodeMapper contribution.ExitStatus = PowerShellExitCodeMapper.GetExitStatus(lastExitCode); } else //at this point we are not able to determine exit status, user needs to fix this... { //=> lets dump what we got before throwing an error... LogStreams(); throw new FatalStepExecutionException( "PowerShellTasklet is not able to determine ExitStatus. ScriptExitStatus is null or (is EXECUTING or UNKNOWN) and " + "PowerShellExitCodeMapper is NOT defined. Please set $global:ScriptExitStatus or define PowerShellExitCodeMapper.", null); } } } if (Logger.IsInfoEnabled) { Logger.Info("PowerShell execution exit status [{0}]", contribution.ExitStatus); } //=> output captured stream data to Log... LogStreams(); } catch (RuntimeException ex) { Logger.Error(ex.Message); throw; } } // end PowerShell Scope //=> close Runspace... runSpace.Close(); //=> we are done... return(RepeatStatus.Finished); } // end of Runspace Scope } // end of TransactionScope }
protected override void OnStart(string[] args) { ServiceStatus.dwCurrentState = ServiceStartPending; ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwWaitHint = ServiceStartTimeout; SetServiceStatus(ServiceHandle, ref ServiceStatus); try { // Initialize Powershell environment InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); initialSessionState.ApartmentState = ApartmentState.STA; initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; initialSessionState.ThreadOptions = PSThreadOptions.UseNewThread; // Initialize Powershell host PsHost = new ServiceHost(this); PowerShellInstance = PowerShell.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(PsHost, initialSessionState); runspace.Open(); PowerShellInstance.Runspace = runspace; // load Powershell Script PowerShellInstance.AddScript(ScriptFilePath, true); // if script terminates service must terminate, too! PowerShellMonitor = (sender, e) => { if (e.InvocationStateInfo.State == PSInvocationState.Completed || e.InvocationStateInfo.State == PSInvocationState.Stopped || e.InvocationStateInfo.State == PSInvocationState.Failed) { WriteEntry(ServiceName, string.Format("{0} script terminated with status '{1}'! - going to stop service!", ServiceName, e.InvocationStateInfo.State), EventLogEntryType.Information); // using no different thread here causes a deadlock! Task.Run(() => { Stop(); }); } }; PowerShellInstance.InvocationStateChanged += PowerShellMonitor; // start script AsyncPowerShell = PowerShellInstance.BeginInvoke(); // Set the variable holding the exit code set by script to default (=0) ExitCodeByScript = 0; // Success. Set the service state to Running. ServiceStatus.dwCurrentState = ServiceRunning; } catch (Exception e) { WriteEntry(ServiceName, string.Format("{0} threw an exception: {1}", ServiceName, e), EventLogEntryType.Error); if (PowerShellInstance != null) { if (PowerShellInstance.Runspace != null) { PowerShellInstance.Runspace.Dispose(); } PowerShellInstance.Dispose(); PowerShellInstance = null; } Power = null; SessionChange = null; Pause = null; Continue = null; Shutdown = null; StopEvent = null; CustomCommand = null; AsyncPowerShell = null; ServiceStatus.dwCurrentState = ServiceStopped; ServiceStatus.dwWin32ExitCode = (int)(Win32Error.ErrorExceptionInService); } finally { ServiceStatus.dwWaitHint = 0; SetServiceStatus(ServiceHandle, ref ServiceStatus); } }
private static ActionResult InvokePowershell(CertificateRequestResult result, string executionPolicy, string scriptFile, Dictionary <string, object> parameters, string scriptContent, PowerShell shell, bool autoConvertBoolean = true) { // ensure execution policy will allow the script to run, default to "Unrestricted", set in service config as "Default" to skip. if (executionPolicy != "Default") { shell.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", executionPolicy) .AddParameter("Scope", "Process") .AddParameter("Force") .Invoke(); } // add script command to invoke if (scriptFile != null) { shell.AddCommand(scriptFile); } else { shell.AddScript(scriptContent); } // pass the result to the script if present if (result != null) { shell.AddParameter("result", result); } // pass parameters to script if present if (parameters != null) { foreach (var a in parameters) { var val = a.Value; if (autoConvertBoolean) { if (val != null && val?.ToString().ToLower() == "true") { val = true; } else if (val != null && val?.ToString().ToLower() == "false") { val = false; } } shell.AddParameter(a.Key, val); } } var errors = new List <string>(); // accumulate output var output = new StringBuilder(); // capture errors shell.Streams.Error.DataAdded += (sender, args) => { var error = shell.Streams.Error[args.Index]; var src = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName; var msg = $"{src}: {error}\n{error.InvocationInfo.PositionMessage}"; output.AppendLine(msg); errors.Add(msg); }; // capture write-* methods (except write-host) shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message); shell.Streams.Debug.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message); shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message); var outputData = new PSDataCollection <PSObject>(); outputData.DataAdded += (sender, args) => { // capture all main output var data = outputData[args.Index]?.BaseObject; if (data != null) { output.AppendLine(data.ToString()); } }; try { var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData); shell.EndInvoke(async); return(new ActionResult(output.ToString().TrimEnd('\n'), !errors.Any())); } catch (ParseException ex) { // this should only happen in case of script syntax errors, otherwise // errors would be output via the invoke's error stream output.AppendLine($"{ex.Message}"); return(new ActionResult(output.ToString().TrimEnd('\n'), false)); } }
public async Task ListenerLoop() { while (!StopServer) { HttpListenerContext context = null; try { context = await Listener.GetContextAsync(); } catch (Exception e) { if (!(e is ObjectDisposedException)) { throw; } } if (StopServer || context == null) { if (Listener != null) { Listener.Close(); } break; } HttpListenerRequest rawRequest = context.Request; HttpListenerResponse rawResponse = context.Response; Log("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl); PolarisRequest request = new PolarisRequest(rawRequest); PolarisResponse response = new PolarisResponse(); string route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/'); PowerShell PowerShellInstance = PowerShell.Create(); PowerShellInstance.RunspacePool = PowerShellPool; try { // Set up PowerShell instance by making request and response global PowerShellInstance.AddScript(PolarisHelperScripts.InitializeRequestAndResponseScript); PowerShellInstance.AddParameter("req", request); PowerShellInstance.AddParameter("res", response); // Run middleware in the order in which it was added foreach (PolarisMiddleware middleware in RouteMiddleware) { PowerShellInstance.AddScript(middleware.ScriptBlock); } PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]); var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => { // Handle errors if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed) { Log(PowerShellInstance.InvocationStateInfo.Reason.ToString()); response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString()); response.SetStatusCode(500); } else if (PowerShellInstance.HadErrors) { var errorsBody = "\n"; for (int i = 0; i < PowerShellInstance.Streams.Error.Count; i++) { errorsBody += "[" + i + "]:\n"; errorsBody += PowerShellInstance.Streams.Error[i].Exception.ToString(); errorsBody += PowerShellInstance.Streams.Error[i].InvocationInfo.PositionMessage + "\n\n"; } response.Send(errorsBody); response.SetStatusCode(500); } // Handle logs if (request.Query[GetLogsString] != null) { var informationBody = "\n"; for (int i = 0; i < PowerShellInstance.Streams.Information.Count; i++) { foreach (var tag in PowerShellInstance.Streams.Information[i].Tags) { informationBody += "[" + tag + "]"; } informationBody += PowerShellInstance.Streams.Information[i].MessageData.ToString() + "\n"; } informationBody += "\n"; // Set response to the logs and the actual response (could be errors) var logBytes = System.Text.Encoding.UTF8.GetBytes(informationBody); var bytes = new byte[logBytes.Length + response.ByteResponse.Length]; logBytes.CopyTo(bytes, 0); response.ByteResponse.CopyTo(bytes, logBytes.Length); response.ByteResponse = bytes; } Send(rawResponse, response); }, null); } catch (Exception e) { if (e is KeyNotFoundException) { Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8"); Log("404 Not Found"); } else { Log(e.Message); throw e; } } } }
void Start(ScriptBlock scriptBlock, Hashtable parameters) { SessionStateAssemblyEntry windowsBase = new SessionStateAssemblyEntry(typeof(Dispatcher).Assembly.ToString()); SessionStateAssemblyEntry presentationCore = new SessionStateAssemblyEntry(typeof(UIElement).Assembly.ToString()); SessionStateAssemblyEntry presentationFramework = new SessionStateAssemblyEntry(typeof(Control).Assembly.ToString()); initialSessionState.Assemblies.Add(windowsBase); initialSessionState.Assemblies.Add(presentationCore); initialSessionState.Assemblies.Add(presentationFramework); initialSessionState.Assemblies.Add(presentationFramework); runspace = RunspaceFactory.CreateRunspace(this.initialSessionState); runspace.ThreadOptions = PSThreadOptions.ReuseThread; runspace.ApartmentState = ApartmentState.STA; runspace.Open(); powerShellCommand = PowerShell.Create(); powerShellCommand.Runspace = runspace; jobThread = powerShellCommand.AddScript("[Threading.Thread]::CurrentThread").Invoke <Thread>()[0]; powerShellCommand.Streams.Error = this.Error; this.Error.DataAdded += new EventHandler <DataAddedEventArgs>(Error_DataAdded); powerShellCommand.Streams.Warning = this.Warning; this.Warning.DataAdded += new EventHandler <DataAddedEventArgs>(Warning_DataAdded); powerShellCommand.Streams.Verbose = this.Verbose; this.Verbose.DataAdded += new EventHandler <DataAddedEventArgs>(Verbose_DataAdded); powerShellCommand.Streams.Debug = this.Debug; this.Debug.DataAdded += new EventHandler <DataAddedEventArgs>(Debug_DataAdded); powerShellCommand.Streams.Progress = this.Progress; this.Progress.DataAdded += new EventHandler <DataAddedEventArgs>(Progress_DataAdded); this.Output.DataAdded += new EventHandler <DataAddedEventArgs>(Output_DataAdded); powerShellCommand.Commands.Clear(); powerShellCommand.Commands.AddScript(scriptBlock.ToString(), false); if (parameters.Count > 0) { powerShellCommand.AddParameters(parameters); } Collection <Visual> output = powerShellCommand.Invoke <Visual>(); if (output.Count == 0) { return; } powerShellCommand.Commands.Clear(); powerShellCommand.Commands.AddCommand("Show-Window").AddArgument(output[0]).AddParameter("OutputWindowFirst"); Object var = powerShellCommand.Runspace.SessionStateProxy.GetVariable("NamedControls"); if (var != null && ((var as Hashtable) != null)) { namedControls = var as Hashtable; } JobDispatcher = Dispatcher.FromThread(jobThread); JobDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(jobDispatcher_UnhandledException); powerShellCommand.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(powerShellCommand_InvocationStateChanged); powerShellCommand.BeginInvoke <Object, PSObject>(null, this.Output); DateTime startTime = DateTime.Now; if (output[0] is FrameworkElement) { while (JobWindow == null) { if ((DateTime.Now - startTime) > TimeSpan.FromSeconds(30)) { this.SetJobState(JobState.Failed); return; } System.Threading.Thread.Sleep(25); } } }
public IAsyncResult RunScript() { IAsyncResult ar = null; Output = new PSDataCollection <PSObject>(); Output.DataAdded += Output_DataAdded; // the streams (Error, Debug, Progress, etc) are available on the PowerShell instance. // we can review them during or after execution. // we can also be notified when a new item is written to the stream (like this): // \Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll var initial = InitialSessionState.CreateDefault(); using (Runspace runspace = RunspaceFactory.CreateRunspace(initial)) { runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); //try { // Logger.WriteMessage(LogLevel.Info, $"Set-ExecutionPolicy Unrestricted"); // runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Force"); //} catch (Exception ex) { Logger.WriteMessage(LogLevel.Error, $"{ex.Message}"); } try { Logger.WriteMessage(LogLevel.Info, $"Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force"); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force"); } catch (Exception ex) { Logger.WriteMessage(LogLevel.Error, $"{ex.Message}"); } var cmd = new Command(@"invoke-command"); cmd.Parameters.Add(new CommandParameter("Scriptblock", //, text)); ScriptBlock.Create(@".\" + Script))); cmd.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); ps.Commands.AddCommand(cmd); this.PS = ps; ps.Streams.Error.DataAdded += Error_DataAdded; try { Parse.TryBind(ps); } catch (MissingMethodException) {; } // Consul failure System.MissingMethodException: Method not found: // 'System.Management.Automatio Management.Automation.InformationRecord > System.Management.Automation.PSDataStreams.get_Info IAsyncResult async = ps.BeginInvoke <PSObject, PSObject>(null, Output); ar = async; if (!async.IsCompleted) { try { ar.AsyncWaitHandle.WaitOne(); StringBuilder sb = new StringBuilder(); foreach (PSObject result in ps.EndInvoke(async)) { sb.AppendLine(result.ToString()); } Logger.WriteMessage(LogLevel.Info, $"{sb.ToString()}"); } catch {; } } } return(ar); }
private async Task<bool> RunScript(string path) { PowerShellInstance = PowerShell.Create(); PowerShellInstance.AddScript(LoadScript(path)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.SourceRepoUserName)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.SourceRepoPassword)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.TargetRepoUserName)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.TargetRepoPassword)); PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += outputCollection_DataAdded; PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded; IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject,PSObject>(null, outputCollection); while (result.IsCompleted == false) { await Task.Delay(100); } return PowerShellInstance.HadErrors; }
protected override void BeginProcessing() { // Build the results ArrayList final = new ArrayList(); int c = 0; int count = InputObject.Count; if (MaxThreads < 20) { MaxThreads = 20; } using (RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(1, MaxThreads)) { try { runspacePool.Open(); ProgressRecord progressRecord = new ProgressRecord(1, "Action in progress...", "Processing..."); foreach (object obj in InputObject) { PowerShell powerShell = PowerShell.Create() .AddScript(ScriptBlock) .AddArgument(obj); try { powerShell.AddParameters(ArgumentList); } catch (Exception) { } powerShell.RunspacePool = runspacePool; IAsyncResult psAsyncResult = powerShell.BeginInvoke(); c++; int pVal = (c / count) * 100; string sVal = String.Format("{0:N0}", pVal); int perc = int.Parse(sVal); string activity = c + " of " + count + " threads completed"; if (NoProgress.IsPresent == false) { progressRecord.PercentComplete = perc; progressRecord.Activity = activity; progressRecord.StatusDescription = perc + "% complete"; WriteProgress(progressRecord); } PSDataCollection <PSObject> psOutput = powerShell.EndInvoke(psAsyncResult); final.Add(psOutput); powerShell.Dispose(); } // End foreach if (NoProgress.IsPresent == false) { progressRecord.PercentComplete = 100; progressRecord.StatusDescription = "100% complete"; WriteProgress(progressRecord); } } catch (Exception) { throw; } runspacePool.Close(); runspacePool.Dispose(); } // End using // Output to console WriteObject(final.ToArray(), true); } // End begin