HomeJourneyResumeContactBlog

← Blog

Automating actions in Windows 10


January 05, 2020

Writing the script

I needed a way to monitor delete events in a specific folder. Although Windows 10 offers multiple ways to do track events, I decided to try DIY-ing it. So I wrote this PowerShell script:

$FolderToWatch = 'D:\Downloads' # Directory that will be tracked
$FilesToWatch = '*.*' # Events involving all file types will be reported
$EventToListen = 'Deleted' # Only delete events will be reported
$Log = 'D:\Downloads\log.txt' # File where the logs will be stored

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$Watcher = New-Object -TypeName 'System.IO.FileSystemWatcher'
$Watcher.Path = $FolderToWatch
$Watcher.Filter = $FilesToWatch
$Watcher.IncludeSubdirectories = $True
$Watcher.EnableRaisingEvents = $True

### DEFINE ACTIONS THAT WILL BE RUN AFTER AN EVENT IS DETECTED
$Action = {
    $DeletedPath = $Event.SourceEventArgs.FullPath
    $LogEntry = "$(Get-Date), $DeletedPath"
    Add-content -LiteralPath $Log -Value $LogEntry
}

### DECIDE WHICH EVENTS SHOULD BE WATCHED
$WatcherEvent = Register-ObjectEvent -InputObject $Watcher -EventName $EventToListen -Action $action

while ($WatcherEvent.JobStateInfo.State -in @([Management.Automation.JobState]::NotStarted, [Management.Automation.JobState]::Running)) {
    Wait-Event -SourceIdentifier $EventToListen
}

What this script does is it adds an entry in a .txt file when a file is deleted. The entry contains the date of the deletion and the path of the affected file. Example:

01/05/2020 16:49:37, D:\Downloads\test.jpg

Running on startup

  1. Run Get-ExecutionPolicy in PowerShell, it should return Unrestricted

    • If it doesn’t, set it to unrestricted by running this command in PowerShell as an Administrator: Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine
  2. Open Task Scheduler
  3. Create Basic Task

    • Enter a name for the task and click Next
    • Select When I log on as the trigger and click Next
    • Select Start a program as the trigger and click Next
    • Enter %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe as the program and add the following arguments: -WindowStyle Hidden -File "C:\PATH TO SCRIPT.ps1" and click Next basic task
  4. Click Finish

Sai Krishna

Written by Boris Yordanov.

Psst! Wanna hire me?

Here's my resume