Monday, August 1, 2016

PowerShell script for automatically putting diffierent kinds of downloaded files in different places

Somebody asked for a way to automatically move things out of the Downloads folder into different places depending on what kind of file each is. I figured the easiest way to approach that is to just check for files there every so often and process each appropriately. I made this script:

$places = @{txt='?\Documents\TextFiles'; exe='?\Documents\NewApps'}

$userprof = [Environment]::ExpandEnvironmentVariables('%USERPROFILE%')
cd ($userprof + '\Downloads')
Do {
  dir -File | % {
    If ($_.Extension.Length -gt 0) {
      $ext = $_.Extension.Substring(1).ToLowerInvariant()
    } Else {
      $ext = 'NOEXT'
    }
    If (-not $places.ContainsKey($ext)) {$ext = 'DEFAULT'}
    If ($places.ContainsKey($ext)) {
      $dest = $places[$ext].Replace('?', $userprof)
      move $_ -Dest $dest
    }
  }
  Start-Sleep -Seconds 5
} While ($true)

The first line defines which file types should go where. A question mark in the destination is replaced with the path to the root of the user profile. Extensionless files will be processed by a NOEXT entry if present; files of types not present in that dictionary will be handled by the DEFAULT entry if it exists, otherwise they'll be left in place.

The script runs in the background and only wakes up every five seconds (as seen in the second to last line). That background task can be started with this batch command:

powershell -Command "Start-Process -WindowStyle Hidden -FilePath powershell -ArgumentList 'C:\path\to\your\script.ps1'"

No comments:

Post a Comment