다음을 통해 공유


Events01 샘플

이 샘플에서는 사용자가 System.IO.FileSystemWatcher발생한 이벤트에 등록할 수 있도록 하는 cmdlet을 만드는 방법을 보여 줍니다. 이 cmdlet을 사용하면 사용자가 특정 디렉터리에서 파일을 만들 때 실행할 작업을 등록할 수 있습니다. 이 샘플은 기본 클래스를 Microsoft.PowerShell.Commands.ObjectEventRegistrationBase 파생됩니다.

Visual Studio를 사용하여 샘플을 빌드하는 방법

  1. Windows PowerShell 2.0 SDK가 설치되어 있는 상태에서 Events01 폴더로 이동합니다. 기본 위치는 C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\Events01입니다.

  2. 솔루션(.sln) 파일의 아이콘을 두 번 클릭합니다. 그러면 Microsoft Visual Studio에서 샘플 프로젝트가 열립니다.

  3. 빌드 메뉴에서 빌드 솔루션 선택하여 기본 \bin 또는 \bin\debug 폴더에서 샘플에 대한 라이브러리를 빌드합니다.

샘플을 실행하는 방법

  1. 다음 모듈 폴더를 만듭니다.

    [user]\Documents\WindowsPowerShell\Modules\events01

  2. 샘플의 라이브러리 파일을 모듈 폴더에 복사합니다.

  3. Windows PowerShell을 시작합니다.

  4. 다음 명령을 실행하여 Windows PowerShell에 cmdlet을 로드합니다.

    Import-Module events01
    
  5. Register-FileSystemEvent cmdlet을 사용하여 TEMP 디렉터리 아래에 파일을 만들 때 메시지를 작성하는 작업을 등록합니다.

    Register-FileSystemEvent $Env:TEMP Created -Filter "*.txt" -Action { Write-Host "A file was created in the TEMP directory" }
    
  6. TEMP 디렉터리 아래에 파일을 만들고 작업이 실행됩니다(메시지가 표시됨).

이 샘플 출력은 다음 단계를 수행하여 결과를 생성합니다.

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
1               26932870-d3b... NotStarted False                                 Write-Host "A f...

Set-Content $Env:TEMP\test.txt "This is a test file"
A file was created in the TEMP directory

요구 사항

이 샘플에는 Windows PowerShell 2.0이 필요합니다.

입증합니다

이 샘플에서는 다음을 보여 줍니다.

이벤트 등록을 위해 cmdlet을 작성하는 방법

이 cmdlet은 Microsoft.PowerShell.Commands.ObjectEventRegistrationBase 클래스에서 파생되며, 이 클래스는 Register-*Event cmdlet에 공통된 매개 변수를 지원합니다. Microsoft.PowerShell.Commands.ObjectEventRegistrationBase에서 파생된 cmdlet은 특정 매개 변수를 정의하고 GetSourceObject 재정의하고 추상 메서드를 GetSourceObjectEventName 경우에만 필요합니다.

예시

이 샘플에서는 System.IO.FileSystemWatcher발생한 이벤트에 등록하는 방법을 보여 줍니다.

namespace Sample
{
    using System;
    using System.IO;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using Microsoft.PowerShell.Commands;

    [Cmdlet(VerbsLifecycle.Register, "FileSystemEvent")]
    public class RegisterObjectEventCommand : ObjectEventRegistrationBase
    {
        /// <summary>The FileSystemWatcher that exposes the events.</summary>
        private FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();

        /// <summary>Name of the event to which the cmdlet registers.</summary>
        private string eventName = null;

        /// <summary>
        /// Gets or sets the path that will be monitored by the FileSystemWatcher.
        /// </summary>
        [Parameter(Mandatory = true, Position = 0)]
        public string Path
        {
            get
            {
                return this.fileSystemWatcher.Path;
            }

            set
            {
                this.fileSystemWatcher.Path = value;
            }
        }

        /// <summary>
        /// Gets or sets the name of the event to which the cmdlet registers.
        /// <para>
        /// Currently System.IO.FileSystemWatcher exposes 6 events: Changed, Created,
        /// Deleted, Disposed, Error, and Renamed. Check the documentation of
        /// FileSystemWatcher for details on each event.
        /// </para>
        /// </summary>
        [Parameter(Mandatory = true, Position = 1)]
        public string EventName
        {
            get
            {
                return this.eventName;
            }

            set
            {
                this.eventName = value;
            }
        }

        /// <summary>
        /// Gets or sets the filter that will be user by the FileSystemWatcher.
        /// </summary>
        [Parameter(Mandatory = false)]
        public string Filter
        {
            get
            {
                return this.fileSystemWatcher.Filter;
            }

            set
            {
                this.fileSystemWatcher.Filter = value;
            }
        }

        /// <summary>
        /// Derived classes must implement this method to return the object that generates
        /// the events to be monitored.
        /// </summary>
        /// <returns> This sample returns an instance of System.IO.FileSystemWatcher</returns>
        protected override object GetSourceObject()
        {
            return this.fileSystemWatcher;
        }

        /// <summary>
        /// Derived classes must implement this method to return the name of the event to
        /// be monitored. This event must be exposed by the input object.
        /// </summary>
        /// <returns> This sample returns the event specified by the user with the -EventName parameter.</returns>
        protected override string GetSourceObjectEventName()
        {
            return this.eventName;
        }
    }
}

또한 참조하십시오