Compartilhar via


Amostra Events01

Este exemplo mostra como criar um cmdlet que permite que o usuário se registre para eventos gerados pelo System.IO.FileSystemWatcher. Com esse cmdlet, os usuários podem registrar uma ação a ser executada quando um arquivo é criado em um diretório específico. Este exemplo deriva da classe base Microsoft.PowerShell.Commands.ObjectEventRegistrationBase.

Como criar o exemplo usando o Visual Studio

  1. Com o SDK do Windows PowerShell 2.0 instalado, navegue até a pasta Events01. A localização predefinida é C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\Events01.

  2. Clique duas vezes no ícone do arquivo de solução (.sln). Isso abre o projeto de exemplo no Microsoft Visual Studio.

  3. No menu Criar, selecione Criar solução para criar a biblioteca para o exemplo nas pastas \bin ou \bin\debug padrão.

Como executar o exemplo

  1. Crie a seguinte pasta de módulo:

    [user]\Documents\WindowsPowerShell\Modules\events01

  2. Copie o arquivo de biblioteca do exemplo para a pasta do módulo.

  3. Inicie o Windows PowerShell.

  4. Execute o seguinte comando para carregar o cmdlet no Windows PowerShell:

    Import-Module events01
    
  5. Use o cmdlet Register-FileSystemEvent para registrar uma ação que gravará uma mensagem quando um arquivo for criado no diretório TEMP.

    Register-FileSystemEvent $Env:TEMP Created -Filter "*.txt" -Action { Write-Host "A file was created in the TEMP directory" }
    
  6. Crie um arquivo no diretório TEMP e observe que a ação é executada (a mensagem é exibida).

Esta é uma saída de exemplo que resulta seguindo estas etapas.

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

Requisitos

Este exemplo requer o Windows PowerShell 2.0.

Demonstra

Este exemplo demonstra o seguinte.

Como gravar um cmdlet para registro de evento

O cmdlet deriva da classe Microsoft.PowerShell.Commands.ObjectEventRegistrationBase, que fornece suporte para parâmetros comuns aos cmdlets Register-*Event. Cmdlets derivados de Microsoft.PowerShell.Commands.ObjectEventRegistrationBase precisam apenas definir seus parâmetros específicos e substituir os métodos abstratos GetSourceObject e GetSourceObjectEventName.

Exemplo

Este exemplo mostra como registrar-se para eventos gerados pelo 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;
        }
    }
}

Consulte Também