Dela via


GetProc02 (C#) – kodexempel

Följande kod visar implementeringen av en Get-Process cmdlet som accepterar kommandoradsindata. Observera att den här implementeringen definierar en parameter för att tillåta kommandoradsinmatning, och den använder metoden Name WriteObject(System.Object, System.Boolean) som utdatamekanism för att skicka utdataobjekt till pipelinen.

Kodexempel

namespace Microsoft.Samples.PowerShell.Commands
{
    using System;
    using System.Diagnostics;
    using System.Management.Automation;     // Windows PowerShell namespace.
   #region GetProcCommand

   /// <summary>
   /// This class implements the get-proc cmdlet.
   /// </summary>
   [Cmdlet(VerbsCommon.Get, "Proc")]
   public class GetProcCommand : Cmdlet
   {
      #region Parameters

       /// <summary>
       /// The names of the processes to act on.
       /// </summary>
      private string[] processNames;

      /// <summary>
      /// Gets or sets the list of process names on which 
      /// the Get-Proc cmdlet will work.
      /// </summary>
      [Parameter(Position = 0)]
      [ValidateNotNullOrEmpty]
      public string[] Name
      {
         get { return this.processNames; }
         set { this.processNames = value; }
      }

      #endregion Parameters

      #region Cmdlet Overrides

      /// <summary>
      /// 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.
      /// </summary>
      protected override void ProcessRecord()
      {
          // If no process names are passed to the cmdlet, get all 
          // processes.
          if (this.processNames == null)
          {
              WriteObject(Process.GetProcesses(), true);
          }
          else
          {
              // If process names are passed to cmdlet, get and write 
              // the associated processes.
              foreach (string name in this.processNames)
              {
                  WriteObject(Process.GetProcessesByName(name), true);
              }
          } // if (processNames...
      } // ProcessRecord

      #endregion Cmdlet Overrides
   } // End GetProcCommand class.

   #endregion GetProcCommand
}

Se även

Windows PowerShell SDK