将新文件夹添加到位置时的触发器脚本

时间:2012-05-10 07:29:07

标签: powershell automation

我正在自动化一个进程,并且已经为此创建了一个PowerShell脚本。现在我需要制作一些东西,每次将新文件夹添加到特定位置时都会调用该脚本,即删除新构建。 我该怎么用呢WCF太多了吗?如果没有,为此获得任何线索?任何有用的链接。 或者是另一个更好的PowerShell脚本吗?

请记住,我也需要检查子文件夹。

感谢。

2 个答案:

答案 0 :(得分:5)

Personnaly我使用System.IO.FileSystemWatcher

$folder = 'c:\myfoldertowatch'
$filter = '*.*'                             
$fsw = New-Object IO.FileSystemWatcher $folder, $filter 
$fsw.IncludeSubdirectories = $true              
$fsw.NotifyFilter = [IO.NotifyFilters]'DirectoryName' # just notify directory name events
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {  ... do my stuff here } # and only when is created

使用此功能停止观看活动

Unregister-Event -SourceIdentifier FileCreated

答案 1 :(得分:0)

试试这个:

$fsw = New-Object System.IO.FileSystemWatcher -Property @{
    Path = "d:\temp"
    IncludeSubdirectories = $true #monitor subdirectories within the specified path
}

$event = Register-ObjectEvent -InputObject $fsw –EventName Created -SourceIdentifier fsw -Action {

    #test if the created object is a directory
    if(Test-Path -Path $EventArgs.FullPath -PathType Container)
    {
        Write-Host "New directory created: $($EventArgs.FullPath)"  
        # run your code/script here
    }
}