Skip to content

Instantly share code, notes, and snippets.

@otonii
Last active November 1, 2023 14:31
Show Gist options
  • Save otonii/8f8f7d002a3674614d212d9aa593e8f6 to your computer and use it in GitHub Desktop.
Save otonii/8f8f7d002a3674614d212d9aa593e8f6 to your computer and use it in GitHub Desktop.
oh-my-posh

oh-my-posh

Deprecated: Use https://github.com/otonii/meu-terminal, esse carinha aqui não será mais atualizado.

Terminal Image

Obter a versão mais recente da Galeria do PowerShell

Antes de atualizar o PowerShellGet, você sempre deve instalar o provedor do NuGet mais recente. Em uma sessão do PowerShell com privilégios elevados, execute os comandos a seguir.

Install-PackageProvider -Name NuGet -Force
Exit

Para instalar o PowerShellGet no Windows 10, no Windows Server 2016, em qualquer sistema com o WMF 5.0 ou 5.1 instalado ou em qualquer sistema com o PowerShell 6, execute os comandos a seguir em uma sessão do PowerShell com privilégios elevados.

Install-Module -Name PowerShellGet -Force
Exit

Use o Update-Module para obter versões mais recentes.

Update-Module -Name PowerShellGet
Exit

Liberando a execução de scripts

Eu precisei liberar a execução para ele poder carregar os arquivos de configurações q alguns comando que usaremos a seguir.

# Liberar para todos os usuários
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

# ou liberar para o usuário atual
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Instalação

Instale posh-git e oh-my-posh:

Install-Module posh-git -Scope CurrentUser
Install-Module oh-my-posh -RequiredVersion 2.0.496 -Force -Scope CurrentUser

Ative o Prompt

# Iniciando configurações iniciais
Set-Prompt

# Alterando o tema
Set-Theme Agnoster

Caso esteja executando no PS Core, instale também a nova versão do PSReadLine

Install-Module -Name PSReadLine -AllowPrerelease -Scope CurrentUser -Force -SkipPublisherCheck

Para habilitar o engine, edite seu perfil do PowerShell

# Cria o arquivo
if (!(Test-Path -Path $PROFILE )) { New-Item -Type File -Path $PROFILE -Force }

# Abre o arquivo para alterações
notepad $PROFILE

# ou você pode alterar direto no code
code $PROFILE

Adicione essas linhas ao seu arquivo de configurações

# Importando módulos
Import-Module posh-git
Import-Module oh-my-posh
Import-Module PSReadLine

# Definindo o tema
Set-Theme Agnoster

# Autocomplete - Teclas de atalho
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward

# Intellisense - Funcionamento
Set-PSReadLineOption -ShowToolTips
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -HistoryNoDuplicates

# Configurando cores do prompt
Set-PSReadLineOption -Colors @{
  # The color of the continuation prompt.
  ContinuationPrompt = [ConsoleColor]::White
  # The emphasis color. For example, the matching text when searching history.
  Emphasis           = [ConsoleColor]::Cyan
  # The error color. For example, in the prompt.
  Error              = [ConsoleColor]::Red
  # The color to highlight the menu selection or selected text.
  Selection          = [ConsoleColor]::White
  # The default token color.
  Default            = [ConsoleColor]::White
  # The comment token color.
  Comment            = [ConsoleColor]::DarkGreen
  # The keyword token color.
  Keyword            = [ConsoleColor]::Green
  # The string token color.
  String             = [ConsoleColor]::Yellow
  # The operator token color.
  Operator           = [ConsoleColor]::DarkGray
  # The variable token color.
  Variable           = [ConsoleColor]::Red
  # The command token color.
  Command            = [ConsoleColor]::Green
  # The parameter token color.
  Parameter          = [ConsoleColor]::Cyan
  # The type token color.
  Type               = [ConsoleColor]::White
  # The number token color.
  Number             = [ConsoleColor]::DarkYellow
  # The member name token color.
  Member             = [ConsoleColor]::White
  # The intellisense color.
  InlinePrediction = [ConsoleColor]::DarkGray
}

Theme

Esse é o tema que eu utilizo, alterei um dos temas padrões do oh-my-posh. Para ativar o tema, basta copiar o arquivo otonii.pms1 na pasta indicada em $ThemeSettings.MyThemesLocation (a pasta padrão é a ~\Documents\WindowsPowerShell\PoshThemes)

Depois basta atualizar no seu arquivo de configurações.

Set-Theme otonii

Outras configurações

Removendo a mensagem de incio do powershell

Tem duas formas de fazer a remoção, uma é adicionar o comando Clear-Host no inicio do arquivo de configurações.

# Limpando Console
Clear-Host

# Importando módulos
...

A segunda forma é adicionar a flag -nologo na invocação do PowerShell.

// Arquivo de configuração do windows-terminal (https://github.com/microsoft/terminal)
{
  // ...
  "profiles": {
    "defaults": {
      "useAcrylic": true,
      "acrylicOpacity": 0.7,
      "cursorShape": "filledBox",
      "colorScheme": "Dracula",
      "fontFace": "Fira Code",
      "startingDirectory": ".",
      "fontSize": 14,
      "padding": "8, 8, 8, 8"
    },
    "list": [
      {
        // Make changes here to the powershell.exe profile.
        "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
        "name": "Windows PowerShell",
        "commandline": "powershell.exe -nologo", // flag -nologo aqui
        "hidden": false
      }
      // ...
    ]
  },
  // ...
  "schemes": [
    {
      "name": "Dracula",
      "background": "#272935",
      "black": "#21222C",
      "blue": "#BD93F9",
      "cyan": "#8BE9FD",
      "foreground": "#F8F8F2",
      "green": "#50FA7B",
      "purple": "#FF79C6",
      "red": "#FF5555",
      "white": "#F8F8F2",
      "yellow": "#FFB86C",
      "brightBlack": "#6272A4",
      "brightBlue": "#D6ACFF",
      "brightCyan": "#A4FFFF",
      "brightGreen": "#69FF94",
      "brightPurple": "#FF92DF",
      "brightRed": "#FF6E6E",
      "brightWhite": "#F8F8F2",
      "brightYellow": "#FFFFA5"
    }
  ]
}

Alterando o comando ls pra ficar parecido com o do unix.

Copie o arquivo powerls.psm1 para pasta Scripts no diretório do arquivo profile com o seguinte conteúdo. E adicione o código abaixo no arquivo de configurações. Preferencialmente no final do arquivo

$ROOT = Split-Path -Parent $MyInvocation.MyCommand.Path

# Sobrescrevendo a função ls
Import-Module $ROOT\Scripts\powerls.psm1
Set-Alias -Name ls -Value PowerLS -Option AllScope
#requires -Version 2 -Modules posh-git
function Write-Theme {
param(
[bool]
$lastCommandFailed,
[string]
$with
)
#check the last command state and indicate if failed
$promtSymbolColor = $sl.Colors.PromptSymbolColor
If ($lastCommandFailed) {
$promtSymbolColor = $sl.Colors.WithForegroundColor
}
#check for elevated prompt
If (Test-Administrator) {
$prompt += Write-Prompt -Object "# " -ForegroundColor $sl.Colors.SessionInfoColor
}
$user = $sl.CurrentUser
if (Test-NotDefaultUser($user)) {
$prompt += Write-Prompt -Object ($user) -ForegroundColor $sl.Colors.UsernameColor
$prompt += Write-Prompt -Object " in " -ForegroundColor $sl.Colors.DefaultText
}
# Writes the drive portion
$drive = $sl.PromptSymbols.HomeSymbol
if ($pwd.Path -ne $HOME) {
$drive = "$(Split-Path -path $pwd -Leaf)"
}
$prompt += Write-Prompt -Object $drive -ForegroundColor $sl.Colors.DriveForegroundColor
$status = Get-VCSStatus
if ($status) {
$prompt += Write-Prompt -Object " on " -ForegroundColor $sl.Colors.DefaultText
$prompt += Write-Prompt -Object "$($sl.PromptSymbols.GitIndicator) $($status.Branch) " -ForegroundColor $sl.Colors.GitBranchColor
$hasIndicator = $false
if ($status.Working.Length -gt 0) {
$prompt += Write-Prompt -Object ($sl.PromptSymbols.GitUnstagedIndicator) -ForegroundColor $sl.Colors.GitUnstaged
$hasIndicator = $true
}
if ($status.HasIndex) {
$prompt += Write-Prompt -Object ($sl.PromptSymbols.GitStagedIndicator) -ForegroundColor $sl.Colors.GitStaged
$hasIndicator = $true
}
if ($status.HasUntracked) {
$prompt += Write-Prompt -Object ($sl.PromptSymbols.GitUntrackedIndicator) -ForegroundColor $sl.Colors.GitUntracked
$hasIndicator = $true
}
if ($status.AheadBy -gt 0) {
$prompt += Write-Prompt -Object ($sl.PromptSymbols.GitAheadIndicator) -ForegroundColor $sl.Colors.GitAhead
$hasIndicator = $true
}
if ($status.BehindBy -gt 0) {
$prompt += Write-Prompt -Object ($sl.PromptSymbols.GitBehindIndicator) -ForegroundColor $sl.Colors.GitBehind
$hasIndicator = $true
}
if ($hasIndicator) {
$prompt += " "
} else {
$prompt += Write-Prompt -Object ($sl.PromptSymbols.GitCleanIndicator) -ForegroundColor $sl.Colors.GitClean
}
}
# Writes the postfix to the prompt
$prompt += Write-Prompt -Object " $($sl.PromptSymbols.PromptIndicator) " -ForegroundColor $promtSymbolColor
$prompt
}
$sl = $global:ThemeSettings #local settings
$sl.PromptSymbols.PromptIndicator = [char]::ConvertFromUtf32(0x276F)
$sl.PromptSymbols.GitIndicator = [char]::ConvertFromUtf32(0xE0A0)
$sl.PromptSymbols.GitCleanIndicator = [char]::ConvertFromUtf32(0x2713)
$sl.PromptSymbols.GitAheadIndicator = [char]::ConvertFromUtf32(0x25B2)
$sl.PromptSymbols.GitBehindIndicator = [char]::ConvertFromUtf32(0x25BC)
$sl.PromptSymbols.GitStagedIndicator = [char]::ConvertFromUtf32(0x25CF)
$sl.PromptSymbols.GitUnstagedIndicator = [char]::ConvertFromUtf32(0x25CF)
$sl.PromptSymbols.GitUntrackedIndicator = [char]::ConvertFromUtf32(0x25CF)
$sl.Colors.DefaultText = [ConsoleColor]::White
$sl.Colors.GitBranchColor = [ConsoleColor]::Magenta
$sl.Colors.GitClean = [ConsoleColor]::Green
$sl.Colors.GitAhead = [ConsoleColor]::Cyan
$sl.Colors.GitBehind = [ConsoleColor]::Magenta
$sl.Colors.GitStaged = [ConsoleColor]::Green
$sl.Colors.GitUnstaged = [ConsoleColor]::DarkYellow
$sl.Colors.GitUntracked = [ConsoleColor]::Red
$sl.Colors.PromptSymbolColor = [ConsoleColor]::Green
$sl.Colors.DriveForegroundColor = [ConsoleColor]::Cyan
$sl.Colors.WithForegroundColor = [ConsoleColor]::Red
$sl.Colors.UsernameColor = [ConsoleColor]::Yellow
$sl.Colors.SessionInfoColor = [ConsoleColor]::DarkYellow
# Copiei de https://github.com/JRJurman/PowerLS
# Só alterei a cor dos 'normal files'
<#
.Synopsis
Powershell unix-like ls
Written by Jesse Jurman (JRJurman)
.Description
A colorful ls
.Parameter Redirect
The first month to display.
.Example
# List the current directory
PowerLS
.Example
# List the parent directory
PowerLS ../
#>
function PowerLS {
param(
[string]$redirect = "."
)
write-host "" # add newline at top
# get the console buffersize
$buffer = Get-Host
$bufferwidth = $buffer.ui.rawui.buffersize.width
# get all the files and folders
$childs = Get-ChildItem $redirect
# get the longest string and get the length
$lnStr = $childs | select-object Name | sort-object { "$_".length } -descending | select-object -first 1
$len = $lnStr.name.length
# keep track of how long our line is so far
$count = 0
# extra space to give some breather space
$breather = 4
# for every element, print the line
foreach ($e in $childs) {
$newName = $e.name + (" "*($len - $e.name.length+$breather))
$count += $newName.length
# determine color we should be printing
# Blue for folders, Green for files, and Gray for hidden files
if (($newName -match "^\..*$") -and (Test-Path ($redirect + "\" + $e) -pathtype container)) { #hidden folders
$newName = $e.name + "\" + (" "*($len - $e.name.length+$breather - 1))
write-host $newName -nonewline -foregroundcolor darkcyan
}
elseif (Test-Path ($redirect + "\" + $e) -pathtype container) { #normal folders
$newName = $e.name + "\" + (" "*($len - $e.name.length+$breather - 1))
write-host $newName -nonewline -foregroundcolor cyan
}
elseif ($newName -match "^\..*$") { #hidden files
write-host $newName -nonewline -foregroundcolor darkgray
}
elseif ($newName -match "\.[^\.]*") { #normal files
write-host $newName -nonewline -foregroundcolor Yellow
}
else { #others...
write-host $newName -nonewline -foregroundcolor gray
}
if ( $count -ge ($bufferwidth - ($len+$breather)) ) {
write-host ""
$count = 0
}
}
write-host "" # add newline at bottom
write-host "" # add newline at bottom
}
export-modulemember -function PowerLS
@Daniel-Vinicius
Copy link

@otonii, abraços, 🚀

@SergioBurlamaK
Copy link

Boa noite! No meu esta ocorrendo dois problemas. O primeiro seria esse aviso
Screenshot_1

O segundo seria todos esses erros logo apos eu adicionar os comando:
{
// ...
"profiles": {
"defaults": {
"useAcrylic": true,
"acrylicOpacity": 0.7,
"cursorShape": "filledBox",
"colorScheme": "Dracula",
"fontFace": "Fira Code",
"startingDirectory": ".",
"fontSize": 14,
"padding": "8, 8, 8, 8"
},
"list": [
{
// Make changes here to the powershell.exe profile.
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"name": "Windows PowerShell",
"commandline": "powershell.exe -nologo", // flag -nologo aqui
"hidden": false
}
// ...
]
},
// ...
"schemes": [
{
"name": "Dracula",
"background": "#272935",
"black": "#21222C",
"blue": "#BD93F9",
"cyan": "#8BE9FD",
"foreground": "#F8F8F2",
"green": "#50FA7B",
"purple": "#FF79C6",
"red": "#FF5555",
"white": "#F8F8F2",
"yellow": "#FFB86C",
"brightBlack": "#6272A4",
"brightBlue": "#D6ACFF",
"brightCyan": "#A4FFFF",
"brightGreen": "#69FF94",
"brightPurple": "#FF92DF",
"brightRed": "#FF6E6E",
"brightWhite": "#F8F8F2",
"brightYellow": "#FFFFA5"
}
]
}
Screenshot_2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment