#================================================= # Author: Kulverstukas # Date: 2018.02.08 # Website: http://9v.lt # Description: # Move files to a subfolder based on datetime # in the filename. If that datetime has passed # then that file needs to be moved. #================================================= #-------- USER DEFINED VARIABLES -------- # folder to scan for files # without slash at the end $SCAN_PATH = "files" # subfolder to move the files # without slash at the end $MV_FOLDER = "files\old" # file filter; set to * for everything $FILTER = "*.txt" # regex filter for datetime in the filename # use \d{4}.\d{1,2}.\d{1,2}( \d{1,2}.\d{1,2})? # for a format: "2018-03-02 12.01" (or without the time) # needs to have a group for hours!! $REGEX_FILTER = "\d{4}.\d{1,2}.\d{1,2}( \d{1,2}.\d{1,2})?" # date and time format in the filename # this needs to match the regex pattern above $FILE_DATETIME_FORMAT = "yyyy-MM-dd H.m" # this is for file names without hours $FILE_DATE_FORMAT = "yyyy-MM-dd" #---------------------------------------- $currDate = Get-Date # create a containing folder if it doesn't exist if (!(Test-Path $MV_FOLDER)) { New-Item -ItemType Directory -Path $MV_FOLDER | Out-Null } # get all file names matching a pattern $files = Get-Childitem $SCAN_PATH -Filter $FILTER | Where-Object { $_ -Match $REGEX_FILTER } Foreach ($file in $files) { # -match in this context returns True if anything was matched # and global var $matches contains matched substrings if ($file -match $REGEX_FILTER) { try { $timeFormat = if ($matches[1]) { $FILE_DATETIME_FORMAT } else { $FILE_DATE_FORMAT } $fileDatetime = [DateTime]::ParseExact($matches[0], $timeFormat, $null) if ($fileDatetime -lt $currDate) { Move-Item -Path ($SCAN_PATH+"\"+$file) -Destination $MV_FOLDER } } catch { Write-Host ("Error processing file '"+$file+"':") -ForegroundColor red Write-Host (" "+$_.Exception.Message) -ForegroundColor red } } }