Custom PowerShell prompts [closed]

拈花ヽ惹草 提交于 2020-07-04 07:47:06

问题


I'm looking for different examples of custom Powershell prompt function implementations. If you have a custom implementation of your own please post the script. Links to existing resources are good as well.

Bonus points for posting a screenshot of what your prompt actually looks like (a preview).


回答1:


This is modified version of jaykul's prompt. The benefit is that

-there is a current history id, so you can invoke previous items from history very easily (you know the id) -it's a little reminder - I add my tasks to the prompt so I don't forget them (see the 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's 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




回答2:


Here's 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 ' '
}

It uses this helper function:

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')
}



回答3:


Here is my prompt function

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 '>'
    ' '
}



回答4:


i often use posh as a calc, so i set $ans variable. https://connect.microsoft.com/PowerShell/feedback/ViewFeedback.aspx?FeedbackID=386493

PS > 100
100
PS > $ans * 9
900
PS > $ans*$ans
810000




回答5:


Here's mine. Just has the history ID at each command so I can easily identify the ID of the command. I also use the windowtitle to give me the current working directory rather than have it displayed in the prompt itself.

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 " "

One thing that many people forget is to deal with in custom prompts is the nested prompt. Note that I check $nestedPromptLevel and add an arrow for each nested level.

Andy




回答6:


I tend to re-type

function prompt { "PS> " }

every time I am preparing examples I can copy/paste to someone, especially when I'm in cumbersome long paths which would only distract.

And I still plan to write a decent prompt function which shows me the drive and a useful approximation on the location by either using the current directory (without the path that led to there) or (if it's numeric) the next higher level too. But that's probably pretty specific to my own filesystem here. And I never was bothered enough by the default prompt to actually do it :-)



来源:https://stackoverflow.com/questions/1338453/custom-powershell-prompts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!