通过Powershell扫描Excel工作表中文件的属性

时间:2018-06-26 08:21:45

标签: powershell automation filereader

我有一个任务,需要扫描存储文件的某些目录所指示的所有文件的属性。我需要我的代码来读取以下由分隔符“”分隔的以下信息,该信息存储在.txt文件中,如下所示(该目录由我自己在自己的设备上组成,然后继续制作一些空白的.xlsx文件,测试我的代码:

Jakarta,C:\\temp\Hfolder,C:\temp\Lfolder

我目前有如下代码:

$LocContent = Import-Csv "C:\temp\Location.txt" # -Header $fileHeaders
ForEach($line in $LocContent){C:\temp\test1.csv -NoTypeInformation 
#split fields into values
      $line = $LocContent -split (",")
      $country = $line[0]
      $hDrivePath = $line[1]
      $lDrivePath = $line[2]
      Get-ChildItem $hDrivePath -force -include *.xlsx, *.accdb, *.accde, *.accdt, *.accdr -Recurse
      Get-ChildItem $lDrivePath -force -include *.xlsx, *.accdb, *.accde, *.accdt, *.accdr -Recurse
      ? {
         $_.LastWriteTime -gt (Get-Date).AddDays(-5) 
      }
      Select-Object -Property Name, Directory, @{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}}, CreationTime, LastAccessTime, @{N="Location";E={$country}}, @{N='size in MB';E={$_.Length/1024kb}} | Export-Csv 
}

但是,分配给我输出信息的.csv文件上没有输出。我的代码有什么问题? 谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码中存在几个缺陷:

  • Select既没有-InputObject也没有任何管道输入,因此没有输出
  • 您应该决定是否将C:\temp\Location.txt视为
    具有Get-Content和拆分的文本文件
    或作为带有标头的csv
    或没有标题,然后将其提供给导入。
  • Get-ChildItem输出不会通过管道传递到任何地方,也不会存储在变量中,因此会转到屏幕。
  • Export-Csv需要导出到的文件名。

尝试以下未经测试的脚本:

## Q:\Test\2018\06\26\SO_51038180.ps1
$fileHeaders = @('country','hDrivePath','lDrivePath')
$extensions  = @('*.xlsx','*.accdb','*.accde','*.accdt','*.accdr')

$LocContent = Import-Csv "C:\temp\Location.txt" -Header $fileHeaders

$NewData = ForEach($Row in $LocContent){
    Get-ChildItem $Row.hDrivePath,$Row.lDrivePath -Force -Include $extensions -Recurse |
        Where-Object LastWriteTime -gt (Get-Date).AddDays(-5) |
            Select-Object -Property Name, 
                Directory, 
                @{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}}, 
                CreationTime, 
                LastAccessTime, 
                @{N="Location";E={$Row.country}}, 
                @{N='size in MB';E={$_.Length/1024kb}}
}
# you choose what to do with the result uncomment the desired

$NewData | Format-Table -Auto
# $NewData | Out-Gridview
# $NewData | Export-Csv '.\NewData.csv' -NoTypeInformation