Skip to content

Instantly share code, notes, and snippets.

@peaeater
Created January 5, 2017 17:06
Show Gist options
  • Save peaeater/681e39d539febf226035e28c6e42e070 to your computer and use it in GitHub Desktop.
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.
<#
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