powershell - Trouble converting dates using _.LastWriteTime -


i writing powershell script searches network location , if file created in 2011 or 2012, writes filename log, sum of 2011/12 files created.

i getting exception when attempts convert date , time of file creation , compare date range.

<#checks 1 network location files 2011.  gets name of file , adds count 2011, writes log.  repeats 2012.#>     new-item c:\users\logs\yearlog.txt -type file -force     $path = "\\path"     $log = "c:\users\log"     $date2011 = "2011"     $date2012 = "2012"     write-progress -activity "compiling data" -status "progress:"     $x = 0     "$date2011 files" | add-content $log      get-childitem -path $path -recurse | where-object {$_.lastwritetime -gt (12/31/2010) -and $_lastwritetime -lt (01/01/2012) |     foreach {         $filename = $_.fullname         $x++         "$filename" | add-content $movelog     }      "$date2011 total files = $x" | add-content $log     $x = 0     "$date2012 files" | add-content $log      get-childitem -path $path -recurse | where-object {$_.lastwritetime -gt (12/31/2011) -and $_lastwritetime -lt (01/01/2013) |     foreach {         $filename = $_.fullname         $x++         "$filename" | add-content $log     }     "$date2012 total files = $x" | add-content $log } } 

key issue: braces in clause unbalanced , pipeline broken.

additional fixes:

  • compare year directly since have datetime object
  • used formatting variables in strings, it's easier when start dealing indexes
  • use -begin clause on foreach initialize counter

anyway, here's fixed version, converted function can pick path, year, , select log output folder

function yearlog {     param(         [parameter(mandatory=$true)][string]$path,         [parameter(mandatory=$true)][string]$logfolder,         [parameter(mandatory=$true)][int]$year     )      $log = '{0}\filelog-{1}.txt' -f $logfolder, $year      if(test-path -path:$log) {          remove-item -force -path:$log      }      'files found {0}:' -f $year | add-content $log      get-childitem -path $path -recurse |          where-object { ($_.lastwritetime.year -gt ($year-1)) -and ($_.lastwritetime.year -lt ($year+1)) } |         foreach -begin { $x = 0 } -process {             $x++ | out-null             $_.fullname | add-content $log         }      'total found {0}: {1}' -f $year, $x  | add-content $log     'log written items in {0} {1}: {2}' -f $path, $year, $log | write-host  }  <# usage:         yearlog -path:$env:programfiles -logfolder:$env:temp -year:2012 #> 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -