I'm watching specific folder using powershell code. But how can I escape some folder like .git folder and file like log.txt? Like if I'm watching all changes and create events in this folder name 'test'. But whenever i save something change event occurs and it commit and push it to bitbucket. At same time .git folder also trigger the change event because of commit and push. And that creates the loop.
Here is my code:
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "path of test folder"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Write-Host $path
if ($path -contains '\.git\') {
}
else{
Add-content "\log.txt" -value $logline
cd test
git add .
git commit -am "made auto changes"
git push origin master
}
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {sleep 5}
You have a few options to filter a string based on your example (all of these assume $path
is a [System.String]
type and not [System.IO.FileInfo]
or [System.IO.DirectoryInfo]
):
Regex
:
if ($path -notmatch '\\\.git\\') {
String.Contains
:
if (-not $path.Contains('\.git\') {
Wildcard
:
if ($path -notlike '*\.git\*') {