Powershell脚本从数组中查找文件年龄

时间:2019-01-11 21:46:18

标签: arrays powershell

我正在使用Powershell脚本读取多个共享上的CreationTime筛选的文件属性。这些脚本偶尔会起作用。当我使用单个路径时,它的效果很好,但是当我将文件夹路径添加到数组时,却得到了混合结果。最令人不安的结果是它成功找到并读取了所有路径,然后将所有内容包括在c:windows \ system32下。共享为空时,也会出现相同的异常情况。

所以我要完成的是:

  1. 阅读股票列表
  2. 读取通过“ CreationTime”和“ Archive”属性过滤的每个共享内容。
  3. 将结果保存到csv文件中。
  4. 如果文件不为空,请将结果写入事件日志。

这是代码

$timer = (Get-Date -Format yyy-MM-dd-HHmm)
$Date=(Get-Date).AddHours(-3)
$FolderList = "C:\Software\Scripts\FolderList.txt"
$Folders = get-content $FolderList
$Filepath = "C:\Software\Scripts"
$filename = "$Filepath\" + $timer + "OldFiles.csv"

foreach ($Folder in $Folders)

{
Get-ChildItem $Folder | Where-Object { $_.CreationTime -lt $Date -and $_.Attributes -band [System.IO.FileAttributes]::Archive} | Select Attributes, CreationTime, Fullname | Export-Csv -Path $filename -NoTypeInformation
}

if ( (get-childitem $filename).length -eq 0 )

{

exit
}


  else{

#Write to OpsMgr Log
$Message = get-content $filename 
Write-EventLog -LogName "Operations Manager" -Source "Health Service Script" -EventID 402 -EntryType Information -Message "Old files found. $Message"

}

1 个答案:

答案 0 :(得分:1)

此(未经测试的)脚本可能会执行您想要的操作:

$Date = (Get-Date).AddHours(-3)

$FolderList = "C:\Software\Scripts\FolderList.txt"
$Folders    = Get-Content $FolderList
$Filepath   = "C:\Software\Scripts"

$timer    = (Get-Date -Format yyyy-MM-dd-HHmm)
$filename = Join-Path $Filepath ("{0}_OldFiles.csv" -f $timer)

$Data = foreach ($Folder in $Folders){
    Get-ChildItem $Folder | 
      Where-Object { $_.CreationTime -lt $Date -and 
                     $_.Attributes -band [System.IO.FileAttributes]::Archive} | 
        Select Attributes, CreationTime, Fullname 
}


if ($Data.Count){
    #Write to OpsMgr Log
    $Data | Export-Csv -Path $filename -NoTypeInformation
    $Message = $Data | ConvertTo-Csv
    Write-EventLog -LogName "Operations Manager" -Source "Health Service Script" `
                   -EventID 402 -EntryType Information `
                   -Message "Old files found. $Message"
}