首页 > 解决方案 > 计算目录中的文件数以及文件夹数

问题描述

目前,我可以将列表导出到文本文件并按共享名称分隔它们。我的问题是:我希望能够将目录中的文件数以及文件夹数计算到单独的文本文件中。

我想以这种格式处理文本文件,$hostname-$sharename-count.txt

例如:

我想要的输出:

1000 #文件夹数
150 #文件数

这是我到目前为止所拥有的:

$outputDir = 'C:\Output'
$Shares    = Get-WmiObject Win32_Share -Filter "not name like '%$'"

$re = ($Shares | ForEach-Object {[Regex]::Escape($_.Path)}) -join '|'
foreach ($Share in $Shares) {
    $result  = (Get-ChildItem -Path $Share.Path -File -Recurse | Select-Object -Expand FullName) -replace "^($re)\\"
    # output the results per share in a text file
    $fileOut = Join-Path -Path $outputDir -ChildPath ('{0}-{1}.txt' -f $env:COMPUTERNAME, $Share.Name)
    $result | Out-File -FilePath $fileOut -Force
}

标签: powershell

解决方案


您可以简单地扩展您拥有的代码,如下所示:

$outputDir = 'C:\Output'
$Shares    = Get-WmiObject Win32_Share -Filter "not name like '%$'"

$re = ($Shares | ForEach-Object {[Regex]::Escape($_.Path)}) -join '|'
foreach ($Share in $Shares) {
    $files   = (Get-ChildItem -Path $Share.Path -File -Recurse | Select-Object -Expand FullName) -replace "^($re)\\"
    # output the list of files per share in a text file
    $fileOut = Join-Path -Path $outputDir -ChildPath ('{0}-{1}.txt' -f $env:COMPUTERNAME, $Share.Name)
    $files | Out-File -FilePath $fileOut -Force

    # output the count results for files and folders per share in a text file
    $folders = Get-ChildItem -Path $Share.Path -Directory -Recurse
    $content = 'Folders: {0}{1}Files:   {2}' -f $folders.Count, [Environment]::NewLine, $files.Count
    $fileOut = Join-Path -Path $outputDir -ChildPath ('{0}-{1}-count.txt' -f $env:COMPUTERNAME, $Share.Name)
    $content | Out-File -FilePath $fileOut -Force
}

PS如果共享中存在任何此类文件,您可以将开关添加-ForceGet-ChildItemcmdlet 以获取列出的隐藏或系统文件


推荐阅读