powershell - 计算目录中的文件数以及文件夹数
问题描述
目前,我可以将列表导出到文本文件并按共享名称分隔它们。我的问题是:我希望能够将目录中的文件数以及文件夹数计算到单独的文本文件中。
我想以这种格式处理文本文件,$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
}
解决方案
您可以简单地扩展您拥有的代码,如下所示:
$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如果共享中存在任何此类文件,您可以将开关添加-Force
到Get-ChildItem
cmdlet 以获取列出的隐藏或系统文件
推荐阅读
- css - Rails 5.2 背景图像未出现(使用 ERB 到 URL)
- c# - 如何将可变长度的模型列表传递给方法
- python-3.x - 将列表分成大约 5K 个字符
- jquery - 无法让 jQuery 追加处理字符串
- memory-leaks - 需要帮助调查复杂 TCL 应用程序中的内存泄漏
- angularjs - 如何在angularjs中启用本地缓存
- xml - 使用 XElement 创建 XML 时解析错误
- javascript - 如何在会话或 cookie 中存储用 HTML 和 JavaScript 编写的表单中的数据,以便在访问表单时使用 PHP 进行预加载
- html - 背景图像未显示在 div 元素内
- core-image - CIWarpKernel 中的清除颜色