Trigger script when a new folder is added to the location

I am automating the process and already made a powershell script for this. Now I need to do something that will call this script every time a new folder is added to a specific location, i.e. a new assembly will be deleted. What should I use for this. Is WCF Too Much? And if not, do you have any conclusions? Any useful links. Or is this another script utility for this?

Keep in mind that I need to check subfolders as well.

Thank.

+3
source share
2 answers

Personnaly I am using 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

Use this to stop viewing events.

Unregister-Event -SourceIdentifier FileCreated
+5
source

Try the following:

$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
    }
}
0
source

All Articles