PowerShell 5.1中Get-ChildItem如何实现带统计的宽格式排序列表?
PowerShell v5.1完全可以原生实现该需求,无需调用cmd.exe,你可以通过Get-ChildItem配合格式化命令直接实现,以下是可直接使用的实现方案:
基础实现代码
你可以将以下代码添加到PowerShell的$Profile配置文件中,启动时会自动加载:
function Get-WideDir { # 获取当前目录下的所有项,默认按名称字母序排序 $allItems = Get-ChildItem # 输出自适应宽度的多列列表 $allItems | Format-Wide -Property Name -AutoSize # 统计目录和文件总数 $dirCount = ($allItems | Where-Object { $_.PSIsContainer }).Count $fileCount = ($allItems | Where-Object { !$_.PSIsContainer }).Count Write-Host "`n总目录数:$dirCount 总文件数:$fileCount" } # 可自定义别名,匹配你之前的调用习惯,比如设置为dir Set-Alias dir Get-WideDir -Option AllScope
扩展优化版本
如果需要支持自定义路径、显示隐藏文件,可以使用扩展版本:
function Get-WideDir { param( [Parameter(Position = 0)] [string]$Path = $PWD.Path, [switch]$Force ) $allItems = Get-ChildItem -Path $Path -Force:$Force $allItems | Format-Wide -Property Name -AutoSize $dirCount = ($allItems | Where-Object PSIsContainer).Count $fileCount = ($allItems | Where-Object -Not PSIsContainer).Count Write-Host "`n路径 $Path 下共有 $dirCount 个目录,$fileCount 个文件" }
调用时可以使用Get-WideDir -Force显示隐藏文件,或者Get-WideDir C:\xxx查看指定路径的列表。
内容的提问来源于stack exchange,提问作者b4iknew
相关产品推荐
相关产品推荐

