Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Using Powershell to monitor file changes then execute a command

Posted on 2016-08-03
5
Medium Priority
?
1,196 Views
Last Modified: 2016-08-04
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

0
Comment
Question by:Garrett
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 13

Accepted Solution

by:
Dustin Saunders earned 2000 total points
ID: 41741207
Create a file system watcher to do the unblock.

$folder = 'c:\test\' 
$filter = '*.*'  

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
$name = $folder + $Event.SourceEventArgs.Name 
Unblock-File $name
} 

Open in new window


Change $folder with your folder and the $filter if it's only a specific file type.
1
 
LVL 13

Expert Comment

by:Dustin Saunders
ID: 41741209
You can unregister the watcher (turn it off) with:
Unregister-Event FileCreated 

Open in new window

0
 
LVL 1

Author Comment

by:Garrett
ID: 41741622
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.
0
 
LVL 13

Expert Comment

by:Dustin Saunders
ID: 41741774
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.
1
 
LVL 1

Author Comment

by:Garrett
ID: 41742367
You're correct about the office files!
Thank you so much. I appreciate your help and explanation!
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A small collection of useful tips and tricks for Windows 10 users that I decided to write as a result of recent questions that were asked and answered at Experts Exchange. Two short video tutorials included. Enjoy..
In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
The Task Scheduler is a powerful tool that is built into Windows. It allows you to schedule tasks (actions) on a recurring basis, such as hourly, daily, weekly, monthly, at log on, at startup, on idle, etc. This video Micro Tutorial is a brief intro…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question