共用方式為


GetProcessSample03 範例

此範例示範如何實作 Cmdlet,以擷取本機電腦上的進程。 它提供 Name 參數,可接受管線中的物件,或來自屬性名稱與參數名稱相同之對象的屬性的值。 此 Cmdlet 是 Windows PowerShell 2.0 所提供之 Get-Process Cmdlet 的簡化版本。

如何使用 Visual Studio 建置範例

  1. 安裝 Windows PowerShell 2.0 SDK 後,流覽至 GetProcessSample03 資料夾。 預設位置為 C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\GetProcessSample03

  2. 按兩下解決方案 (.sln) 檔案的圖示。 這會在 Visual Studio 中開啟範例專案。

  3. 在 [建置] 功能表中,選取 [建置方案],以在預設 \bin\bin\debug 資料夾中建置範例的連結庫。

如何執行範例

  1. 建立下列模組資料夾:

    [user]\Documents\WindowsPowerShell\Modules\GetProcessSample03

  2. 將範例元件複製到模組資料夾。

  3. 啟動 Windows PowerShell。

  4. 執行下列命令,將元件載入 Windows PowerShell:

    Import-Module getprossessample03

  5. 執行下列命令以執行 Cmdlet:

    Get-Proc

需求

此範例需要 Windows PowerShell 2.0。

演示

此範例示範下列專案。

  • 使用 Cmdlet 屬性宣告 Cmdlet 類別。

  • 使用 Parameter 屬性宣告 Cmdlet 參數。

  • 指定參數的位置。

  • 指定參數會從管線取得輸入。 輸入可以取自物件或屬性名稱與參數名稱相同之對象的 屬性的值。

  • 宣告參數輸入的驗證屬性。

範例

此範例示範 Get-Proc Cmdlet 的實作,其中包含接受管線輸入的 Name 參數。

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 retrieved by the cmdlet.
    /// </summary>
    private string[] processNames;

    /// <summary>
    /// Gets or sets the names of the
    /// process that the cmdlet will retrieve.
    /// </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);
        }
      } // End if (processNames ...)
    } // End ProcessRecord.

    #endregion Overrides
  } // End GetProcCommand.
  #endregion GetProcCommand
}

另請參閱