本帖最后由 flashercs 于 2021-2-27 23:17 编辑
先测试目录。- <#*,:&cls
- @echo off
- pushd "%~dp0"
- powershell -NoProfile -ExecutionPolicy RemoteSigned -Command ". ([ScriptBlock]::Create((Get-Content -LiteralPath \"%~0\" -ReadCount 0 | Out-String ))) "
- popd
- pause
- exit /b
- #>
- # 给指定文件夹及其子文件夹加前缀(保留原文件夹名) 前缀内容为ss001(编码) 200p(文件夹内文件数) 2.1GB(文件夹总大小) +原文件夹名
- # 文件夹Depth从0开始,现在只改名Depth=1
- # ss001 200p 2.1GB 原文件夹名
- # ss002 4500p 3.1GB 原文件夹名
- # ss003 5683p 3.8GB 原文件夹名
-
- # 目录列表
- $rootDirs = "D:\sec", "D:\Videos", "D:\image"
-
- function Format-FileSize {
- # output: string
- param (
- [long]$FileSize
- )
- switch ($FileSize) {
- { $_ -ge 1TB } { return "{0:F2}TB" -f ($_ / 1TB) }
- { $_ -ge 1GB } { return "{0:F2}GB" -f ($_ / 1GB) }
- { $_ -ge 1MB } { return "{0:F2}MB" -f ($_ / 1MB) }
- { $_ -ge 1KB } { return "{0:F2}KB" -f ($_ / 1KB) }
- Default { return "{0}Bytes" -f $_ }
- }
- }
- function Get-DirectoryInfo {
- # output: PSCustomObject
- param (
- [string]$DirPath,
- [string]$Prefix = "",
- [int]$Depth = 0,
- [scriptblock]$DepthEval = { $true }
- )
- $psoSize = New-Object psobject -Property ([ordered]@{
- FilesCount = [long]0
- DirectorySize = [long]0
- })
- $index = 0
- Get-ChildItem -LiteralPath $DirPath -Force | ForEach-Object {
- if ($_.PSIsContainer) {
- $index++
- $psoSize.DirectorySize += (Get-DirectoryInfo -DirPath ($_.FullName) -Prefix "ss$($index.ToString().PadLeft(3,[char]'0'))" `
- -Depth ($Depth + 1) -DepthEval $DepthEval).DirectorySize
- } else {
- $psoSize.DirectorySize += $_.Length
- $psoSize.FilesCount += 1
- }
- }
- $fsoInfo = Get-Item $DirPath -Force
- $origName = $fsoInfo.Name -replace "^ss\d+\s+\d+p\s+\S+\s+", ""
- $fmtSize = Format-FileSize -FileSize ($psoSize.DirectorySize)
- # $fmtSize | Write-Host -ForegroundColor Green
- if ((& $DepthEval $Depth)) {
- Rename-Item -LiteralPath $fsoInfo.FullName `
- -NewName (@($Prefix, "$($psoSize.FilesCount)p", ($fmtSize), $origName) -join " ") `
- -Force -Verbose
- }
- $psoSize
- }
-
- foreach ($item in $rootDirs) {
- Get-DirectoryInfo -DirPath $item -Prefix "ss001" -DepthEval { param($depth)$depth -eq 1 }
- }
复制代码
|