이 샘플에서는 로컬 컴퓨터에서 프로세스를 검색하는 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 클래스를 선언합니다.
매개 변수 특성을 사용하여 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
}
또한 참조하십시오
PowerShell