当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] GetProc02 (C#) 示例代码

作者:精品下载站 日期:2024-12-14 02:29:02 浏览:13 分类:玩电脑

GetProc02 (C#) 示例代码


以下代码显示了接受命令行输入的 Get-Process cmdlet 的实现。请注意,此实现定义了一个 Name 参数以允许命令行输入,并且它使用 WriteObject(System.Object,System.Boolean) 方法作为将输出对象发送到管道的输出机制。

代码示例

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
}

参见

Windows PowerShell SDK

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯