Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
В этом примере показано, как создать командлет, позволяющий пользователю регистрировать события, создаваемые System.IO.FileSystemWatcher. С помощью этого командлета пользователи могут зарегистрировать действие для выполнения при создании файла в определенном каталоге. Этот пример является производным от базового класса Microsoft.PowerShell.Commands.ObjectEventRegistrationBase.
Создание примера с помощью Visual Studio
Установив пакет SDK для Windows PowerShell 2.0, перейдите в папку Events01. По умолчанию он расположен в папке
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\Events01
.Дважды щелкните значок для файла решения (.sln). Откроется пример проекта в Microsoft Visual Studio.
В меню Сборка выберите Сборка решения, чтобы создать библиотеку для примера в папках
\bin
по умолчанию или\bin\debug
.
Запуск примера
Создайте следующую папку модуля:
[user]\Documents\WindowsPowerShell\Modules\events01
Скопируйте файл библиотеки для примера в папку модуля.
Запустите Windows PowerShell.
Выполните следующую команду, чтобы загрузить командлет в Windows PowerShell:
Import-Module events01
Используйте командлет Register-FileSystemEvent для регистрации действия, которое будет записывать сообщение при создании файла в каталоге TEMP.
Register-FileSystemEvent $Env:TEMP Created -Filter "*.txt" -Action { Write-Host "A file was created in the TEMP directory" }
Создайте файл в каталоге 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.
Демонстрирует
В этом примере показано следующее.
Создание командлета для регистрации событий
Командлет является производным от класса Microsoft.PowerShell.Commands.ObjectEventRegistrationBase, который обеспечивает поддержку параметров, общих для командлетов Register-*Event
. Командлеты, производные от Microsoft.PowerShell.Commands.ObjectEventRegistrationBase, должны определять только определенные параметры и переопределять 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;
}
}
}
См. также
PowerShell