Пользовательские подсказки PowerShell

Я ищу различные примеры пользовательских реализаций функций Powershell prompt. Если у вас есть пользовательская реализация, отправьте сообщение script. Ссылки на существующие ресурсы также хороши.

Бонусные баллы за публикацию скриншота о том, как выглядит ваше приглашение (предварительный просмотр).

Ответы

Ответ 1

Вот моя оперативная функция

function prompt() {
    if ( Test-Wow64 ) {
        write-host -NoNewLine "Wow64 "
    }
    if ( Test-Admin ) { 
        write-host -NoNewLine -f red "Admin "
    }
    write-host -NoNewLine -ForegroundColor Green $(get-location)
    foreach ( $entry in (get-location -stack)) {
        write-host -NoNewLine -ForegroundColor Red '+';
    }
    write-host -NoNewLine -ForegroundColor Green '>'
    ' '
}

Ответ 2

Это измененная версия подсказки jaykul. Преимущество состоит в том, что

- есть текущий идентификатор истории, поэтому вы можете очень легко ссылаться на предыдущие элементы из истории (вы знаете идентификатор) - немного напоминание - я добавляю свои задачи в приглашение, поэтому не забываю их (см. sshot)

function prompt {
  $err = !$?
  $origOfs = $ofs;
  $ofs = "|"
  $toPrompt = "$($global:__PromptVars)"
  $ofs = $origOfs;
  if ($toPrompt.Length -gt 0) { 
    Write-Host "$($toPrompt) >" -ForegroundColor Green -NoNewline }

  $host.UI.RawUI.WindowTitle = "PS1 > " + $(get-location)

  # store the current color, and change the color of the prompt text
  $script:fg = $Host.UI.RawUI.ForegroundColor
  # If there an error, set the prompt foreground to "Red"
  if($err) { $Host.UI.RawUI.ForegroundColor = 'Red' }
  else { $Host.UI.RawUI.ForegroundColor = 'Yellow' }

  # Make sure that Windows and .Net know where we are at all times
  [Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath

  # Determine what nesting level we are at (if any)
  $Nesting = "$([char]0xB7)" * $NestedPromptLevel

  # Generate PUSHD(push-location) Stack level string
  $Stack = "+" * (Get-Location -Stack).count

  # Put the ID of the command in, so we can get/invoke-history easier
  # eg: "r 4" will re-run the command that has [4]: in the prompt
  $nextCommandId = (Get-History -count 1).Id + 1
  # Output prompt string
  # Notice: no angle brackets, makes it easy to paste my buffer to the web
  Write-Host "[${Nesting}${nextCommandId}${Stack}]:" -NoNewLine

  # Set back the color
  $Host.UI.RawUI.ForegroundColor = $script:fg

  if ($toPrompt.Length -gt 0) { 
      $host.UI.RawUI.WindowTitle = "$($toPrompt) -- " + $host.UI.RawUI.WindowTitle
  }
  " "
}
function AddTo-Prompt($str) {
  if (!$global:__PromptVars) { $global:__PromptVars = @() }
  $global:__PromptVars += $str
}
function RemoveFrom-Prompt($str) {
  if ($global:__PromptVars) {
    $global:__PromptVars = @($global:__PromptVars | ? { $_ -notlike $str })
  }
}

sshot

Ответ 3

Здесь mine:

function prompt {
   # our theme
   $cdelim = [ConsoleColor]::DarkCyan
   $chost = [ConsoleColor]::Green
   $cloc = [ConsoleColor]::Cyan

   write-host "$([char]0x0A7) " -n -f $cloc
   write-host ([net.dns]::GetHostName()) -n -f $chost
   write-host ' {' -n -f $cdelim
   write-host (shorten-path (pwd).Path) -n -f $cloc
   write-host '}' -n -f $cdelim
   return ' '
}

Он использует эту вспомогательную функцию:

function shorten-path([string] $path) {
   $loc = $path.Replace($HOME, '~')
   # remove prefix for UNC paths
   $loc = $loc -replace '^[^:]+::', ''
   # make path shorter like tabs in Vim,
   # handle paths starting with \\ and . correctly
   return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2')
}

Ответ 5

Здесь мой. Просто имеет идентификатор истории в каждой команде, поэтому я могу легко идентифицировать идентификатор команды. Я также использую windowtitle, чтобы дать мне текущий рабочий каталог, а не отображать его в самой строке.

106 >  cat function:\prompt

    $history = @(get-history)
    if($history.Count -gt 0)
{
        $lastItem = $history[$history.Count - 1]
        $lastId = $lastItem.Id
    }

    $nextCommand = $lastId + 1
    $Host.ui.rawui.windowtitle = "PS " + $(get-location)
    $myPrompt = "$nextCommand > "
    if ($NestedPromptLevel -gt 0) {$arrows = ">"*$NestedPromptLevel; $myPrompt = "PS-nested $arrows"}
    Write-Host ($myPrompt) -nonewline
    return " "

Одна вещь, которую забывают многие люди, - это вложенные подсказки в пользовательских приглашениях. Обратите внимание, что я проверяю $nestedPromptLevel и добавляю стрелку для каждого вложенного уровня.

Andy

Ответ 6

Я пытаюсь перепечатать

function prompt { "PS> " }

каждый раз, когда я готовлю примеры, я могу скопировать/вставить кому-то, особенно когда я нахожусь в громоздких длинных дорожках, которые будут только отвлекать.

И я все еще планирую написать приличную функцию подсказки, которая показывает мне диск и полезное приближение по местоположению либо с использованием текущего каталога (без пути, который привел к нему), либо (если он является числовым) следующего более высокого уровня слишком. Но это, вероятно, довольно специфично для моей файловой системы. И я никогда не беспокоился по умолчанию, чтобы на самом деле это сделать: -)