如何在按列列出的网格中编写按字典顺序排序的列表?
我有 Get-ChildItem
的结果,我想迭代这些结果并显示它们的名称。默认情况下,如果我只是使用 Write-Host
,那么我会像这样沿行列出它:
PerfLogs Program Files Program Files (x86) Python31 Temp Users Windows
但是,假设我知道我希望将其拆分为 x 列,我希望输出如下所示:
PerfLogs Python31 Windows
Program Files Temp
Program Files (x86) Users
正如您所看到的,它首先将其沿列列出,然后再横向列出。
知道如何获得这样的输出吗?理想情况下,它会使用最多的列数,以适应屏幕的大小,并将名称与每列的左侧对齐。
更新:感谢 Roman,我现在可以使用目录颜色获得 Linux 风格的“ls”输出。构建他更新的脚本,我有:
function color-ls
{
dir $args | Format-High -Print {
$item = $args
$fore = $host.UI.RawUI.ForegroundColor
$host.UI.RawUI.ForegroundColor = .{
if ($item[1].psIsContainer) {'Blue'}
elseif ($item[1].Extension -match '\.(exe|bat|cmd|ps1|psm1|vbs|rb|reg|dll|o|lib)') {'Red'}
elseif ($item[1].Extension -match '\.(zip|tar|gz|rar)') {'Yellow'}
elseif ($item[1].Extension -match '\.(py|pl|cs|rb|h|cpp)') {'Cyan'}
elseif ($item[1].Extension -match '\.(txt|cfg|conf|ini|csv|log|xml)') {'Green'}
else {$fore}
}
write-host $args[0] -NoNewLine
$host.UI.RawUI.ForegroundColor = $fore
}
}
输出:
I have the result of Get-ChildItem
, and I want to iterate over these, and display their names. By default if I simply use Write-Host
then I get it listed out along the row like this:
PerfLogs Program Files Program Files (x86) Python31 Temp Users Windows
However, say that I know I want it split into x columns, I want the output like this instead:
PerfLogs Python31 Windows
Program Files Temp
Program Files (x86) Users
As you can see, it lists it down the columns first, and then across.
Any idea how to get output like that? Ideally it would use the most # of columns as can fit on screen with the Name aligned to the left in each column.
UPDATE: thanks to Roman, I can now have my linux style 'ls' output with directory colors. Building off his updated script I have:
function color-ls
{
dir $args | Format-High -Print {
$item = $args
$fore = $host.UI.RawUI.ForegroundColor
$host.UI.RawUI.ForegroundColor = .{
if ($item[1].psIsContainer) {'Blue'}
elseif ($item[1].Extension -match '\.(exe|bat|cmd|ps1|psm1|vbs|rb|reg|dll|o|lib)') {'Red'}
elseif ($item[1].Extension -match '\.(zip|tar|gz|rar)') {'Yellow'}
elseif ($item[1].Extension -match '\.(py|pl|cs|rb|h|cpp)') {'Cyan'}
elseif ($item[1].Extension -match '\.(txt|cfg|conf|ini|csv|log|xml)') {'Green'}
else {$fore}
}
write-host $args[0] -NoNewLine
$host.UI.RawUI.ForegroundColor = $fore
}
}
Output:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个有趣的想法和任务。
更新:更新的脚本包含一些修复和改进。它还允许以多种方式自定义输出。请参阅脚本注释中的示例。
脚本格式-High.ps1:
It’s an interesting idea and task.
UPDATE: the updated script contains a few fixes and improvements. It also allows to customize the output in several ways. See examples in the script comments.
Script Format-High.ps1: