Link to home
Start Free TrialLog in
Avatar of Garrett
Garrett

asked on

Using Powershell to monitor file changes then execute a command

So I am trying to make a script that monitors a file for changes and then executes Unblock-File cmdlet from Powershell. I have gotten to this point and PowerShell ISE is throwing a lot of errors at me. This is my first run time working with Powershell so I am wondering if I am on the right track or way off base.
 

strComputer = “.”
 
Set objWMIService = GetObject(“winmgmts:” _
 
    & “{impersonationLevel=impersonate}!\\” & _
 
        strComputer & “\root\cimv2”)
 
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
 
    (“SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE ” _
 
        & “Targetinstance ISA ‘CIM_DirectoryContainsFile’ and ” _
 
            & “TargetInstance.GroupComponent= ” _
 
                & “‘Win32_Directory.Name=””c:\\\\users\garretth\desktop\unblockfolder\””‘”)
 
Do
 
    Set objLatestEvent = colMonitoredEvents.NextEvent
 
    gci C:\users\garretth\desktop\unblockfolder | Unblock-File
 
Loop
 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dustin Saunders
Dustin Saunders
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can unregister the watcher (turn it off) with:
Unregister-Event FileCreated 

Open in new window

Avatar of Garrett
Garrett

ASKER

That you for your response! Super helpful. Is it possible to make it loop or does the $fsw call a Windows service that is always monitoring? My network admin was wondering the system resource use on this as well. It shouldn't be a lot but I was wondering if you had any insight.
You're creating a watcher object, so it will always wait for a file event to occur in the location specified and then trigger (doesn't run like a service or a looping script).  The resource usage is negligible, unless for some reason you are saving and processing thousands of files every few seconds; but I'm guessing based off the unblock command you're just downloading office files you want unblocked.
Avatar of Garrett

ASKER

You're correct about the office files!
Thank you so much. I appreciate your help and explanation!