// // Copyright (c) 2009 Microsoft Corporation. All rights reserved. // // DISCLAIMER OF WARRANTY: The software is licensed “as-is.” You // bear the risk of using it. Microsoft gives no express warranties, // guarantees or conditions. You may have additional consumer rights // under your local laws which this agreement cannot change. To the extent // permitted under your local laws, Microsoft excludes the implied warranties // of merchantability, fitness for a particular purpose and non-infringement. namespace Microsoft.Samples.PowerShell.Commands { using System; using System.Diagnostics; using System.Management.Automation; // Windows PowerShell namespace. #region GetProcCommand /// /// This class implements the get-proc cmdlet. /// [Cmdlet(VerbsCommon.Get, "Proc")] public class GetProcCommand : Cmdlet { #region Parameters /// /// The names of the processes to act on. /// private string[] processNames; /// /// Gets or sets the list of process names on /// which the Get-Proc cmdlet will work. /// [Parameter( Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string[] Name { get { return this.processNames; } set { this.processNames = value; } } #endregion Parameters #region Cmdlet Overrides /// /// The ProcessRecord method calls the Process.GetProcesses /// method to retrieve the processes specified by the Name /// parameter. Then, the WriteObject method writes the /// associated processes to the pipeline. /// protected override void ProcessRecord() { // If no process names are passed to cmdlet, get all // processes. if (this.processNames == null) { WriteObject(Process.GetProcesses(), true); } else { // If process names are passed to the cmdlet, get and write // the associated processes. // If a nonterminating error occurs while retrieving processes, // call the WriteError method to send an error record to the // error stream. foreach (string name in this.processNames) { Process[] processes; try { processes = Process.GetProcessesByName(name); } catch (InvalidOperationException ex) { WriteError(new ErrorRecord( ex, "UnableToAccessProcessByName", ErrorCategory.InvalidOperation, name)); continue; } WriteObject(processes, true); } // foreach (string name... } // else } // ProcessRecord #endregion Overrides } // End GetProcCommand class. #endregion GetProcCommand }