PowerShell: Monitor changes to a folder

This uses a FileSystemWatcher object and its WaitForChanged method, which is rather nifty way to not use much resource to keep track of file system changes. What we’re NOT doing here is polling the folder contents.

I’m then trying a couple of different methods to try and work out, if possible, the user responsible for the changes. This doesn’t always work, but it’s not too bad. You’ll get better info about the user if the folder is being accessed remotely via an SMB share thanks to the Get-SmbOpenFile cmdlet, otherwise I try and get the file owner, or don’t bother at all. Get-SmbOpenFile needs elevated privileges so you’ll need to run this “as administrator”.

$Folder = ’D:\TD2’
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher $Folder
while ($true) {
  $Change = $FileSystemWatcher.WaitForChanged(‘All’, 1000)
  if ($Change.TimedOut -eq $false){
    [string]$User = ""
    $FilePath = Join-Path -Path $Folder -ChildPath $Change.Name
    if(Test-Path -Path $FilePath){
      $SMBUserArray = Get-SmbOpenFile -IncludeHidden | Where-Object -Property Path -Like $FilePath
      if($SMBUserArray.Count -ge 1){
        $User = "SMB: "+$SMBUserArray[0].ClientUserName+" "
      }else{
        try{
          $User = "Owner: "+(Get-Acl -Path $FilePath -ErrorAction Stop).Owner+" "
        }catch{}
      }
    }
    Write-host ($User+$Result.ChangeType+": "+$Result.Name)
  }
}

Press Ctrl-C to abort when you’re done monitoring.

This entry was posted in PowerShell, Security and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s