次の方法で共有


GetProc03 (C#) サンプル コード

次のコードは、パイプライン入力を受け入れることができる Get-Process コマンドレットの実装を示しています。 この実装では、パイプラインの入力を受け入れ、指定された名前に基づいてローカル コンピューターからプロセス情報を取得する Name パラメーターを定義し、パイプラインにオブジェクトを送信するための出力メカニズムとして WriteObject(System.Object,System.Boolean) メソッドを使用します。

Windows Vista および .NET Framework 3.0 ランタイム コンポーネント用の Microsoft Windows ソフトウェア開発キットを使用して、この Get-Proc コマンドレットの C# ソース ファイル (getprov03.cs) をダウンロードできます。 ダウンロード手順については、「Windows PowerShell をインストールして Windows PowerShell SDKをダウンロードする方法」を参照してください。 ダウンロードしたソース ファイルは、<PowerShell Samples> ディレクトリにあります。

コード サンプル

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
}

こちらもご覧ください

Windows PowerShell プログラマ ガイド

Windows PowerShell SDK の