Przykład Events01

W tym przykładzie pokazano, jak utworzyć polecenie cmdlet, które umożliwia użytkownikowi rejestrowanie zdarzeń wywoływanych przez system.IO.FileSystemWatcher. Za pomocą tego polecenia cmdlet użytkownicy mogą zarejestrować akcję do wykonania podczas tworzenia pliku w określonym katalogu. Ten przykład pochodzi z klasy bazowej Microsoft.PowerShell.Commands.ObjectEventRegistrationBase.

Jak skompilować przykład przy użyciu Visual Studio.

  1. Po zainstalowaniu Windows PowerShell 2.0 SDK przejdź do folderu Events01. Domyślna lokalizacja to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\Events01.

  2. Kliknij dwukrotnie ikonę pliku rozwiązania (sln). Spowoduje to otwarcie przykładowego projektu w Microsoft Visual Studio.

  3. W menu Kompilacja wybierz pozycję Build Solution (Skompilowanie rozwiązania). Biblioteka przykładu zostanie sbudowaną w foldery domyślne \bin lub \bin\debug .

Jak uruchomić przykład

  1. Utwórz następujący folder modułu:

    [user]/documents/windowspowershell/modules/events01

  2. Skopiuj plik biblioteki przykładu do folderu module.

  3. Uruchom program Windows PowerShell.

  4. Uruchom następujące polecenie, aby załadować polecenie cmdlet do Windows PowerShell:

    import-module events01
    
  5. Użyj polecenia cmdlet Register-FileSystemEvent, aby zarejestrować akcję, która będzie zapisywać komunikat po utworzeniu pliku w katalogu TEMP.

    Register-FileSystemEvent $env:temp Created -filter "*.txt" -action { Write-Host "A file was created in the TEMP directory" }
    
  6. Utwórz plik w katalogu TEMP i zwróć uwagę, że akcja jest wykonywana (zostanie wyświetlony komunikat).

Jest to przykładowe dane wyjściowe, których wyniki można wykonać, korzystając z tych kroków.

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

Wymagania

Ten przykład wymaga Windows PowerShell 2.0.

Demonstracje

W tym przykładzie przedstawiono następujące informacje.

Jak napisać polecenie cmdlet do rejestracji zdarzeń

Polecenie cmdlet pochodzi od klasy Microsoft.PowerShell.Commands.ObjectEventRegistrationBase, która zapewnia obsługę parametrów wspólnych dla Register-*Event poleceń cmdlet. Polecenia cmdlet pochodzące z klasy Microsoft.PowerShell.Commands.ObjectEventRegistrationBase muszą tylko definiować konkretne parametry i zastępować metody GetSourceObject GetSourceObjectEventName abstrakcyjne i .

Przykład

W tym przykładzie pokazano, jak zarejestrować zdarzenia wywoływane przez 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;
        }
    }
}

Zobacz też

Pisanie polecenia cmdlet programu Windows PowerShell