此範例示範如何撰寫 Cmdlet,以擷取本機電腦上的進程。 它提供 Name 參數,可用來指定要擷取的進程。 此 Cmdlet 是 Windows PowerShell 2.0 所提供之 Get-Process Cmdlet 的簡化版本。
如何使用 Visual Studio 建置範例
安裝 Windows PowerShell 2.0 SDK 後,流覽至 GetProcessSample02 資料夾。 預設位置為
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\GetProcessSample02。按兩下解決方案 (.sln) 檔案的圖示。 這會在 Visual Studio 中開啟範例專案。
在 [建置] 功能表中,選取 [建置方案],以在預設
\bin或\bin\debug資料夾中建置範例的連結庫。
如何執行範例
建立下列模組資料夾:
[user]\Documents\WindowsPowerShell\Modules\GetProcessSample02將範例元件複製到模組資料夾。
啟動 Windows PowerShell。
執行下列命令,將元件載入 Windows PowerShell:
Import-Module getprossessample02執行下列命令以執行 Cmdlet:
Get-Proc
需求
此範例需要 Windows PowerShell 2.0。
演示
此範例示範下列專案。
使用 Cmdlet 屬性宣告 Cmdlet 類別。
使用 Parameter 屬性宣告 Cmdlet 參數。
指定參數的位置。
宣告參數輸入的驗證屬性。
範例
此範例示範包含 Name 參數的 Get-Proc Cmdlet 實作。
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 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 process objects 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);
}
} // End if (processNames...).
} // End ProcessRecord.
#endregion Cmdlet Overrides
} // End GetProcCommand class.
#endregion GetProcCommand
}