Powershell: Properly coloring Get-Childitem output once and for all

后端 未结 6 421
醉梦人生
醉梦人生 2020-12-04 13:14

Edit: Original solution at the bottom of this post. For a more up-to-date solution, see the accepted answer, posted by Thraka.

Colorizing Get-Childit

相关标签:
6条回答
  • 2020-12-04 13:38

    Modifying Out-Default is definitely the way to go. Below a - granted, sloppy - example. I'm using New-CommandWrapper from the PowerShell Cookbook.

    New-CommandWrapper Out-Default `
        -Process {
            if(($_ -is [System.IO.DirectoryInfo]) -or ($_ -is [System.IO.FileInfo]))
            {if(-not ($notfirst)) {
               Write-Host "    Directory: $(pwd)`n"           
               Write-Host "Mode                LastWriteTime     Length Name"
               Write-Host "----                -------------     ------ ----"
               $notfirst=$true
               }
               if ($_ -is [System.IO.DirectoryInfo]) {
               Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10}  {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), $_.length, $_.name) -foregroundcolor "yellow" }
               else {
               Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10}  {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), $_.length, $_.name) -foregroundcolor "green" }
               $_ = $null
            }
    } 
    

    Example Directory Listing

    0 讨论(0)
  • 2020-12-04 13:48

    I could not get the main post to work (tried for about an hour trying to get the components to work without success - probably the solution there could be updated or changed to one of the more up to date solutions?). PSColor looks a good solution, but I looked around and in the end found what (in my opinion) is a much better overall solution including well-tailored color settings and seamless icon support. I've built a script to perform all of the required installation steps (just throw these lines into any Admin PowerShell console and then you just need to remember Set-ConsoleFont "LiterationMono NF" and Set-TerminalIconsColorTheme -Name DevBlackOps to activate in any console (or keep those lines in your $profile):

    ### Install Terminal-Icons (get LiterationMono NF Nerd font, install, add required Console registry key, then install required Modules)
    $url = 'https://github.com/haasosaurus/nerd-fonts/raw/regen-mono-font-fix/patched-fonts/LiberationMono/complete/Literation%20Mono%20Nerd%20Font%20Complete%20Mono%20Windows%20Compatible.ttf'
    $name = "LiterationMono NF"
    $file = "$($env:TEMP)\$($name).ttf"
    # Install-Module BitsTransfer   # Could be required on PS v2
    Start-BitsTransfer -Source $url -Destination $file   # Download the font
    
    $Install = $true  # $false to uninstall (or 1 / 0)
    $FontsFolder = (New-Object -ComObject Shell.Application).Namespace(0x14)   # Must use Namespace part or will not install properly
    $filename = (Get-ChildItem $file).Name
    $filepath = (Get-ChildItem $file).FullName
    $target = "C:\Windows\Fonts\$($filename)"
    
    If (Test-Path $target -PathType Any) { Remove-Item $target -Recurse -Force } # UnInstall Font
    
    If ((-not(Test-Path $target -PathType Container)) -and ($Install -eq $true)) { $FontsFolder.CopyHere($filepath, 16) }   # Following action performs the install, requires user to click on yes
    
    $key = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont'   # Need to set this for console
    Set-ItemProperty -Path $key -Name '000' -Value $name
    
    Write-Host "Install-Module Terminal-Icons (Advanced Coloured dir / ls / gci listings with icons)" -ForegroundColor Yellow -BackgroundColor Black
    Write-Host "   Add-TerminalIconsColorTheme, Add-TerminalIconsIconTheme, Format-TerminalIcons,"
    Write-Host "   Get-TerminalIconsColorTheme, Get-TerminalIconsIconTheme, Get-TerminalIconsTheme,"
    Write-Host "   Set-TerminalIconsColorTheme, Set-TerminalIconsIconTheme, Show-TerminalIconsTheme"
    Write-Host "View Module Contents: " -NoNewLine ; Write-Host "get-command -module terminal-icons" -ForegroundColor Yellow
    
    Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force   # Always need this, required for all Modules
    Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted   # Set Microsoft PowerShell Gallery to 'Trusted'
    Install-Module Terminal-Icons -Scope CurrentUser
    Import-Module Terminal-Icons
    Install-Module WindowsConsoleFonts
    Set-ConsoleFont $name
    Set-TerminalIconsColorTheme -Name DevBlackOps   # After the above are setup, can add this to line to $Profile to always load
    
    0 讨论(0)
  • 2020-12-04 13:53

    Maybe via an Out-Default proxy function.

    0 讨论(0)
  • 2020-12-04 13:54

    I just installed and used https://github.com/Davlind/PSColor which was painless. It supports PSGet so you can install easily with Install-Module PSColor to get it.

    The objects aren't transformed so they still support piping. (It's using the New-CommandWrapper mentioned above)

    It also supports other things like select-string.

    PowerShell Color

    0 讨论(0)
  • 2020-12-04 14:00

    I have another script which takes care of Format-Wide (ls) case and also has better performance by using dictionaries instead of regex: https://github.com/joonro/Get-ChildItem-Color.

    0 讨论(0)
  • 2020-12-04 14:00

    I have another solution. You can just have a custom .format.ps1xml for it, and do some tweaks to make the coloring possible.

    I have my person .format.ps1xml formating file on github.com: https://github.com/ecsousa/PSUtils/blob/master/CustomPSUtils.format.ps1xml

    To use it, all you need to do is:

    Update-FormatData -Prepend CustomPSUtils.format.ps1xml
    

    Also, to make sure you go back to original Console color after a Get-ChildItem, you will need to override prompt function. Something like this:

    function prompt {
        if($global:FSFormatDefaultColor) {
            [Console]::ForegroundColor = $global:FSFormatDefaultColor
        }
    
        "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
    }
    
    0 讨论(0)
提交回复
热议问题