列出文件夹和子文件夹中的文件详细信息

时间:2020-09-17 21:55:38

标签: powershell

我正在尝试获取目录中“父”目录中子目录的文件名。

我设法部分解决了我的问题,但是在最后一个目录中,它正在乘以文件(就像我两次检查此文件夹一样)。 如果我有2个项目,他会将我4个导出到最后一个目录。

我设法从目录中获取文件,但是如果我在根目录(父目录)中有任何文件,则不会列出。

父目录“ \ XML”

  • File1.xlsx
  • File2.txt
  • 文件夹2

Dir“ Folder2”

  • File1.xml
  • File2.xml

因此,在导出的CSV文件中将有4行,这是“ Folder2”文件夹中的重复文件。而且不会将文件带到父文件夹“ XML”文件夹中。

Powershell脚本:

# To execute the script without agreeing with the execution policy
Set-ExecutionPolicy Bypass -Scope Process

# Defines the parent directory, where all files and folders inside it will be
$DirPai = 'D:\Users\F02579\Desktop\XML'

# Variable to store all directories within the parent directory
$DirPastas = (Get-ChildItem -Directory -Recurse $DirPai).FullName

# Variable that will keep the final result
$results = @()

foreach ($Dir in $DirPastas)
{
    # Write the directory name
    Write-Host $Dir
    # Get the file details
    $Arquivos = Get-ChildItem -Path $Dir -Recurse | Select-Object Directory, Name, Lenght, LastWriteTime, @{Name="Extension";Expression={$_.Extension}} #| Where-Object "Extension"-ne ''
    # Store the result for each path
    $results += $Arquivos
}

# Defines the directory to which the final file will be exported
$DiretorioExportacao = 'D:\Users\F02579\Desktop\XML\I_PI_LISTFILES.csv'

# Export the result to CSV in the previously informed directory
$results | Export-Csv -Path $DiretorioExportacao -NoTypeInformation -Encoding UTF8

2 个答案:

答案 0 :(得分:1)

您可以将代码简化为以下内容。

  1. 仅保留第一个Get_ChildItem。删除-Dir开关(即获取文件和文件夹)
  2. 直接管道到选择对象。不要为显式循环而烦恼。

这将给出包含五个项目的结果:四个文件和一个文件夹。

您还输入了“长度”的错字。

干杯。

# To execute the script without agreeing with the execution policy
Set-ExecutionPolicy Bypass -Scope Process

# Defines the parent directory, where all files and folders inside it will be
$DirPai = 'D:\Users\F02579\Desktop\XML'

$results = (Get-ChildItem -Recurse $DirPai) | Select-Object Directory, Name, Length, LastWriteTime, @{Name="Extension";Expression={$_.Extension}} #| Where-Object "Extension"-ne ''

# Defines the directory to which the final file will be exported
$DiretorioExportacao = 'D:\Users\F02579\Desktop\XML\I_PI_LISTFILES.csv'

# Export the result to CSV in the previously informed directory
$results | Export-Csv -Path $DiretorioExportacao -NoTypeInformation -Encoding UTF8

答案 1 :(得分:0)

您已经捕获了所有目录,因此在循环中需要指定-File参数,并且不需要-Recurse参数。

   $Arquivos = Get-ChildItem -Path $Dir -File | 
            Select-Object @{Name="Directory",Expression($Dir),
                    Name, Lenght, LastWriteTime, 
                    @{Name="Extension";Expression={$_.Extension}} 

HTH

相关问题