Powershell 彩色目录列表在格式范围内不正确

Nat*_*ers 5 directory powershell colors

我从http://tasteofpowershell.blogspot.com/2009/02/get-childitem-dir-results-color-coded.html获得了这个彩色目录脚本:

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 {
        $_
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但大多数时候我只想要宽格式的文件名。所以在调用表达式调用之后,我添加了

  Invoke-Expression ("Get-ChildItem $args") |
    %{
      if ($_.GetType().Name -eq 'DirectoryInfo') {
  :
  :
  :
        $_
      }
    } | format-wide -property Name
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个错误。只有第二列的颜色是正确的;每列中的第一个项目采用第二列中项目的颜色。例如,如果我有

> ls

Directory     Program.exe
Run Code Online (Sandbox Code Playgroud)

那么 Directory 和 Program.exe 都将是红色的,即使 Directory 应该是 DarkCyan。我该如何纠正这个问题?

Kei*_*ill 3

与其在向屏幕显示文本之间调整主机的前景色/背景色,不如使用 Write-Host ,它可以让您对显示的文本有更多的控制(您可以控制何时输出换行符),例如:

$_ | Out-String -stream | Write-Host -Fore Red
Run Code Online (Sandbox Code Playgroud)

对于广泛的列表使用,您需要自己处理列格式,除非您想要更新 DirectoryInfo/FileInfo 类型的格式数据 XML。如果您不想这样做,那么您可以用所需的颜色写出每个名称(适当填充)。在最后一列中,将 -NoNewLine 参数设置为 $false:

$width =  $host.UI.RawUI.WindowSize.Width
$cols = 3   
ls | % {$i=0; $pad = [int]($width/$cols) - 1} `
       {$nnl = ++$i % $cols -ne 0; `
        Write-Host ("{0,-$pad}" -f $_) -Fore Green -NoNewLine:$nnl}
Run Code Online (Sandbox Code Playgroud)