Skip to content

Instantly share code, notes, and snippets.

@jancimajek
Last active November 24, 2023 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jancimajek/6559aeb84b6cc00e8825010bf7dd524a to your computer and use it in GitHub Desktop.
Save jancimajek/6559aeb84b6cc00e8825010bf7dd524a to your computer and use it in GitHub Desktop.
Move Windows Screenshot files
# See: https://superuser.com/a/844034/448073
#
# Useful Docs:
# - `Get-EventSubscriber` -- List subscribed events -- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-eventsubscriber?view=powershell-7.3
# - `Register-ObjectEvent` -- Register new event -- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/register-objectevent?view=powershell-7.3
# - `Unregister-Event -SubscriptionId 123` -- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/unregister-event?view=powershell-7.3
$watchFolder = "$env:LOCALAPPDATA\Packages\MicrosoftWindows.Client.CBS_cw5n1h2txyewy\TempState\ScreenClip"
# Define actions after an event is detected
$action = {
$targetFolder = "$env:OneDrive\Pictures\Screenshots"
$logFile = "$HOME\screenshot.log"
$srcPath = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
# See: https://stackoverflow.com/a/24976593/192331
$creationTime = Get-ChildItem "$srcPath" | Select-Object -ExpandProperty CreationTime | Get-Date -Format "yyyy-MM-dd HHmmss"
$filename = "Screenshot $creationTime.png"
$dstPath = "$targetFolder\$filename"
Start-Sleep 1
$logline = "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"), ${changeType}: $srcPath"
Add-Content -Path "$logFile" -value $logline
if (!(Test-Path "$dstPath" -PathType Leaf)) {
Copy-Item "$srcPath" -Destination "$dstPath"
$logline = "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"), Copied: $srcPath -> $dstPath"
Add-Content -Path "$logFile" -value $logline
} else {
$logline = "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"), Skipped: $dstPath"
Add-Content -Path "$logFile" -value $logline
}
}
# Set folder to watch + files to watch + subfolders yes/no
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$watchFolder"
$watcher.Filter = "*.png"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
# Decide which events should be watched
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) { Start-Sleep 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment