Trigger script when new folder has been added to a

2020-03-05 03:44发布

问题:

I'm automating a process and already made a powershell script for that. Now I need to make something which will call that script everytime a new folder has been added to a specific location i.e. a new build is dropped. What should I use for this. Is WCF too much? And if not, got any leads for that? Any useful links. Or is another powershell script better for that?

Keep in mind I need to check subfolders too.

Thanks.

回答1:

Personnaly I'ld use 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 watching event

Unregister-Event -SourceIdentifier FileCreated


回答2:

Try this:

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