我从http://tasteofpowershell.blogspot.com/2009/02/get-childitem-dir-results-color-coded.html获取了这个彩色dir脚本:
function ls {
$regex_opts = ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Compiled)
$fore = $Host.UI.RawUI.ForegroundColor
$compressed = New-Object System.Text.RegularExpressions.Regex('\.(zip|tar|gz|rar)$', $regex_opts)
$executable = New-Object System.Text.RegularExpressions.Regex('\.(exe|bat|cmd|ps1|psm1|vbs|rb|reg|dll|o|lib)$', $regex_opts)
$executable = New-Object System.Text.RegularExpressions.Regex('\.(exe|bat|cmd|ps1|psm1|vbs|rb|reg|dll|o|lib)$', $regex_opts)
$source = New-Object System.Text.RegularExpressions.Regex('\.(py|pl|cs|rb|h|cpp)$', $regex_opts)
$text = New-Object System.Text.RegularExpressions.Regex('\.(txt|cfg|conf|ini|csv|log|xml)$', $regex_opts)
Invoke-Expression ("Get-ChildItem $args") |
%{
if ($_.GetType().Name -eq 'DirectoryInfo') {
$Host.UI.RawUI.ForegroundColor = 'DarkCyan'
$_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($compressed.IsMatch($_.Name)) {
$Host.UI.RawUI.ForegroundColor = 'Yellow'
$_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($executable.IsMatch($_.Name)) {
$Host.UI.RawUI.ForegroundColor = 'Red'
$_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($text.IsMatch($_.Name)) {
$Host.UI.RawUI.ForegroundColor = 'Green'
$_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($source.IsMatch($_.Name)) {
$Host.UI.RawUI.ForegroundColor = 'Cyan'
$_
$Host.UI.RawUI.ForegroundColor = $fore
} else {
$_
}
}
}
它的表现很好,但是大多数情况下,我只需要以宽格式显示文件名。因此,在调用invoke-expression之后,我添加了以下内容:
Invoke-Expression ("Get-ChildItem $args") |
%{
if ($_.GetType().Name -eq 'DirectoryInfo') {
:
:
:
$_
}
} | format-wide -property Name
}
现在我有一个bug。只有第二列的颜色是正确的;每一列的第一个项目都会采用第二列项目的颜色。例如,如果我有:
> ls
Directory Program.exe
即使Directory应该是DarkCyan,但是Directory和Program.exe都会变成红色。我该如何更正呢?
ls
的函数。运行脚本后,您实际上必须通过ls
运行该函数。您可能需要使用. .\color.ps1
命令来源化color.ps1
文件。 - Nathan Shively-Sanders. .\color.ps1
,然后执行 Get-ChildItemColor 命令,您应该能够看到带有颜色输出的结果。 - Keith Hill.\color.ps1
。当我使用. .\color.ps1
时,它就起作用了。 - Leniel Maccaferri