이 샘플에서는 로컬 컴퓨터에서 프로세스를 검색하는 cmdlet을 구현하는 방법을 보여 줍니다. 파이프라인의 개체 또는 속성 이름이 매개 변수 이름과 같은 개체의 속성에서 값을 수락할 수 있는 Name
매개 변수를 제공합니다. 이 cmdlet은 Windows PowerShell 2.0에서 제공하는 Get-Process
cmdlet의 간소화된 버전입니다.
Visual Studio를 사용하여 샘플을 빌드하는 방법
Windows PowerShell 2.0 SDK가 설치된 상태에서 GetProcessSample03 폴더로 이동합니다. 기본 위치는
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\GetProcessSample03
입니다.솔루션(.sln) 파일의 아이콘을 두 번 클릭합니다. 그러면 Visual Studio에서 샘플 프로젝트가 열립니다.
빌드 메뉴에서 빌드 솔루션 선택하여 기본
\bin
또는\bin\debug
폴더에서 샘플에 대한 라이브러리를 빌드합니다.
샘플을 실행하는 방법
다음 모듈 폴더를 만듭니다.
[user]\Documents\WindowsPowerShell\Modules\GetProcessSample03
샘플 어셈블리를 모듈 폴더에 복사합니다.
Windows PowerShell을 시작합니다.
다음 명령을 실행하여 Windows PowerShell에 어셈블리를 로드합니다.
Import-Module getprossessample03
다음 명령을 실행하여 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 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
}
또한 참조하십시오
PowerShell