GetProc03 (C#) – mintakód

Az alábbi kód egy olyan parancsmag megvalósítását mutatja be, amely képes fogadni a Get-Process folyamat által megadott adatokat. Ez az implementáció meghatároz egy paramétert, amely fogadja a folyamat bemenetét, lekéri a folyamatadatokat a helyi számítógépről a megadott nevek alapján, majd a Name WriteObject(System.Object,System.Boolean) metódust használja kimeneti mechanizmusként az objektumok folyamatba való küldése érdekében.

Megjegyzés

Ehhez a Get-Proc-parancsmaghoz a C#-forrásfájlt (getprov03.cs) a Microsoft Windows Vista és a .NET-keretrendszer 3.0 Runtime Components microsoftos Windows Windows Szoftverfejlesztői készletével töltheti le. A letöltési utasításokért lásd: How to Install Windows PowerShell and Download the Windows PowerShell SDK.. A letöltött forrásfájlok a könyvtárban <PowerShell Samples> érhetők el.

Kódminta

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 setsthe list of process names on 
      /// which the Get-Proc cmdlet will work.
      /// </summary>
      [Parameter(
         Position = 0,
         ValueFromPipeline = true,
         ValueFromPipelineByPropertyName = true)]
      [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 the cmdlet, get and write 
              // the associated processes.
              foreach (string name in this.processNames)
              {
                  WriteObject(Process.GetProcessesByName(name), true);
              }
          } // if (processNames ...
      } // ProcessRecord
      #endregion Overrides
   } // End GetProcCommand class.

    #endregion GetProcCommand
}

Lásd még:

Windows PowerShell – programozói útmutató

Windows PowerShell SDK