Created
January 5, 2017 17:06
-
-
Save peaeater/681e39d539febf226035e28c6e42e070 to your computer and use it in GitHub Desktop.
Create web-safe folder from portion of filename taken by supplied regex and move file into it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
For each file: | |
1. take filename or portion of it, | |
2. create web-safe folder from template and filename match, | |
3. move file into new folder. | |
e.g. -format "arnpriorbylaw{0}" -take "(?m)(?i)\s*by-law\s*-\s*(\d{4}A*-\d{2})\s*-\s*.+$" => 'arnpriorbylaw1234-00' | |
#> | |
param( | |
[string]$in, | |
[string]$outdir, | |
[regex]$take = "(.+)", | |
[string]$format = "{0}" | |
) | |
function WebSafe([string]$s) { | |
return $s.ToLowerInvariant().Replace(" ", "-").Replace("&", "-") | |
} | |
$file = get-childitem $in | |
# take filename or portion | |
$file.BaseName -match $take | out-null | |
$folder = WebSafe(($format -f $matches[1])) | |
$folderdir = [System.IO.Path]::Combine($outdir, $folder) | |
# rename original file temporarily in case folder name == filename | |
$filename = $file.Name | |
$temp = "$($file.FullName).tmp" | |
move-item $file.FullName $temp -force | |
# make absolutely brand new folder, destroying any pre-existing folder of that name | |
if (test-path $folderdir) { | |
get-childitem $folderdir -force -recurse | remove-item -force -recurse | |
remove-item $folderdir -force | |
} | |
mkdir $folderdir | out-null | |
# move file to new folder | |
$outfile = [System.IO.Path]::Combine($folderdir, $filename) | |
move-item $temp $outfile -force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment