Nota
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
En este ejemplo se muestra cómo crear un cmdlet que permita al usuario registrarse para eventos generados por System.IO.FileSystemWatcher. Con este cmdlet, los usuarios pueden registrar una acción para ejecutarse cuando se crea un archivo en un directorio específico. Este ejemplo se deriva de la clase base Microsoft.PowerShell.Commands.ObjectEventRegistrationBase.
Cómo compilar el ejemplo mediante Visual Studio
Con el SDK de Windows PowerShell 2.0 instalado, vaya a la carpeta Events01. La ubicación predeterminada es
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\Events01
.Haga doble clic en el icono del archivo de solución (.sln). Se abre el proyecto de ejemplo en Microsoft Visual Studio.
En el menú compilación de, seleccione Compilar solución para compilar la biblioteca para el ejemplo en las carpetas de
\bin
o\bin\debug
predeterminadas.
Cómo ejecutar el ejemplo
Cree la siguiente carpeta de módulo:
[user]\Documents\WindowsPowerShell\Modules\events01
Copie el archivo de biblioteca del ejemplo en la carpeta del módulo.
Inicie Windows PowerShell.
Ejecute el siguiente comando para cargar el cmdlet en Windows PowerShell:
Import-Module events01
Use el cmdlet Register-FileSystemEvent para registrar una acción que escribirá un mensaje cuando se cree un archivo en el directorio TEMP.
Register-FileSystemEvent $Env:TEMP Created -Filter "*.txt" -Action { Write-Host "A file was created in the TEMP directory" }
Cree un archivo en el directorio TEMP y observe que se ejecuta la acción (se muestra el mensaje).
Se trata de una salida de ejemplo que da como resultado estos pasos.
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 ejemplo requiere Windows PowerShell 2.0.
Demostraciones
En este ejemplo se muestra lo siguiente.
Escritura de un cmdlet para el registro de eventos
El cmdlet deriva de la clase Microsoft.PowerShell.Commands.ObjectEventRegistrationBase, que proporciona compatibilidad con parámetros comunes a los cmdlets de Register-*Event
. Los cmdlets derivados de Microsoft.PowerShell.Commands.ObjectEventRegistrationBase solo necesitan definir sus parámetros concretos e invalidar los métodos abstractos GetSourceObject
y GetSourceObjectEventName
.
Ejemplo
En este ejemplo se muestra cómo registrarse para eventos generados por 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;
}
}
}