Advertisement
JoshuaB

SortEach-SchoolYear.ps1

Aug 13th, 2013
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $excluded = @("*.ps1", "*.bat", "*.exe", ".*", "_*")
  2.  
  3. function Move-SchoolYear([string]$folder, [int]$startYear)
  4. {
  5.     $start = '8/1/' + $startYear
  6.     $end = '7/1/' + ($startYear + 1)
  7.  
  8.     # Select only files and exclude the others
  9.     $files = dir *.* -exclude $excluded |
  10.         # Only between the date range
  11.         ? { $_.LastWriteTime -gt $start -AND $_.LastWriteTime -lt $end}
  12.  
  13.     # Skip this grade if we got not files
  14.     if ($files -eq $null -OR $files.Count -eq 0) {
  15.         Write-Host ($folder + ": No files to move")
  16.         return
  17.     }
  18.    
  19.     # Just to make it pretty, check if we only got one file
  20.     if ($files.GetType() -eq [System.IO.FileInfo]) {
  21.         Write-Host ($folder + ": 1 file to move")
  22.     } else {
  23.         Write-Host ($folder + ": " + $files.Count + " files to move")
  24.     }
  25.  
  26.     # Don't make folder it it's already is there
  27.     if (!(Test-Path $folder)) {
  28.         mkdir $folder
  29.     }
  30.    
  31.     $files | ForEach-Object {
  32.         $name = $_.Name
  33.         $source = $name
  34.         $dest = $folder + "\\" + $name
  35.        
  36.         if (Test-Path $dest) {
  37.             Write-Host ("   [!] Failed to move '" + $name + "'. File already exists.")
  38.             continue
  39.         }
  40.        
  41.         try {
  42.             Move-Item $source $dest -ErrorAction Stop
  43.             Write-Host ("   Moved " + $name)
  44.         } catch {
  45.             Write-Host ("   [!] Failed to move '" + $name + "'. " + $_.Exception.Message)
  46.         }
  47.     }
  48. }
  49.  
  50. $grades = @{
  51.     "Grade 10" = 2013;
  52.     "Grade 9" = 2012;
  53.     "Grade 8" = 2011;
  54.     "Grade 7" = 2010;
  55.     "Grade 6" = 2009
  56. }
  57.  
  58. foreach($_ in $grades.GetEnumerator()) {
  59.     Move-SchoolYear $_.Key $_.Value
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement