2013-07-18 146 views
0

我正在编写一个搜索网络位置的Powershell脚本,并且如果该文件是在2011或2012年创建的,然后将文件名写入日志以及所有2011/12的总和创建的文件。使用_.LastWriteTime转换日期的问题

我收到了一个异常,它试图转换文件创建的日期和时间并将其与我的日期范围进行比较。

<#Checks one network location for files from 2011. 
gets the name of that file and adds to the count for 2011, then writes it to a log. 
Repeats for 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 
} 
} 
+1

用引号括起日期:*“12/31/2010”*。否则它会尝试将12除以31,然后再减去2010。 –

+0

谢谢zespri。我应该抓到那个:)显然,这不是我唯一的问题 –

+0

请发送例外文本请 –

回答

1

关键问题:Where子句中的括号不平衡并且管道已损坏。

附加修正:

  • 比较一年内直接既然你已经有了一个DateTime对象
  • 用于字符串格式化变量,当你开始使用索引
  • 使用-BEGIN条款在处理这只是更容易For each to initialize counter

无论如何,这里是一个固定版本,转换为一个函数,以便您可以选择任何路径,年,并选择日志输出文件夹

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 for {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 for {0}: {1}' -f $year, $x | add-content $log 
    'Log written for items in {0} for {1}: {2}' -f $Path, $Year, $log | Write-Host 
} 

<# Usage:  
    YearLog -Path:$ENV:ProgramFiles -LogFolder:$ENV:TEMP -Year:2012 
#> 
+0

非常有帮助,谢谢,以所有贡献者! –