Quantcast
Channel: /r/powershell – How to Code .NET
Viewing all articles
Browse latest Browse all 8793

Question about my PS script that executes a file when there is a change in a directory.

$
0
0

Somewhat new to PS. I have this script i pieced together from the internet that watches a directory of my choice and if a file is created, edited etc.. it launches a file of my choice. It also has a loop to wait for excel to not be open so multiple instances dont occur as well as a filename filter to watch for.

I have multiple versions of the script for different directories and am wondering if i could consolidate to one ps1.
I can put all the files in subdirectories. But can this script be edited to look for multiple filters and based on the filter launch a different file?

 ### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = "C:UsersDIRECTORY" $watcher.Filter = "FILENAME*.*" $watcher.IncludeSubdirectories = $true $watcher.EnableRaisingEvents = $true ### DEFINE ACTIONS AFTER AN EVENT IS DETECTED $action = { $Logfile = "C:powershell-temp.log" $excelrunning = Get-Process excel -ErrorAction SilentlyContinue Add-content $Logfile -value "Script starting..." $keepRunning = $true while ($keepRunning) { $excelrunning = Get-Process excel -ErrorAction SilentlyContinue if (-Not $excelrunning) { Add-content $Logfile -value "Excel NOT running. Opening file..." #Set the file path (can be a network location) $filePath = "C:UsersFILE" $excelObj = New-Object -ComObject Excel.Application $excelObj.Visible = $true #Open the workbook $workBook = $excelObj.Workbooks.Open($filePath) $keepRunning = $false } else { Add-content $Logfile -value "Excel is still running. Waiting..." sleep 5 $keepRunning = $true } } } ### DECIDE WHICH EVENTS SHOULD BE WATCHED Register-ObjectEvent $watcher "Created" -Action $action # Register-ObjectEvent $watcher "Changed" -Action $action # Register-ObjectEvent $watcher "Renamed" -Action $action while ($true) {sleep 5} 

submitted by /u/MatzahBallBackFat
[link] [comments]

The post Question about my PS script that executes a file when there is a change in a directory. appeared first on How to Code .NET.


Viewing all articles
Browse latest Browse all 8793

Latest Images

Trending Articles



Latest Images