I am using the following code on two separate computers. On both computers it is in the $PROFILE.AllUsersAllHosts location.

#http://powershell.com/cs/blogs/tips/archive/2010/11/22/test-admin-privileges.aspx
function Test-Admin {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = new-object Security.Principal.WindowsPrincipal $identity
    $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# Set this global variable so we don't have to check our role on every prompt
$global:AdminPrompt = (Test-Admin)

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

    if($global:AdminPrompt){
        $chost = [ConsoleColor]::Red
    }

    #Set the Window Title
    (Get-Host).UI.RawUI.WindowTitle = pwd

    #Write the prompt
    write-host "$([char]0x0A7) " -n -f $cloc
    #alt method - write-host ([net.dns]::GetHostName()) -n -f $chost
    write-host $env:COMPUTERNAME -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) {
    if(-NOT $global:AdminPrompt){
        $loc = $path.Replace($HOME, '~')
    } else {
        $loc = $path
    }
    # 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')
} 

On one computer, when I invoke a new Powershell with RunAs, it hits the AdminPrompt test in shorten-path and dies. It leaves me with PS:> at the end of the command prompt. However, if I dot-source the profile, it correctly shortens the path for the prompt.

Example:

§ COMPUTERNAME {PS:>
§ COMPUTERNAME {PS:> . $PROFILE.AllUsersAllHosts
§ COMPUTERNAME {C:\W\System32}

On the other computer, I get the expected behavior when I enter a Powershell with RunAs from the beginning. It makes trouble shooting difficult since I can't replicate the problem!

有帮助吗?

解决方案

Check $error - you may find a hint as to what went wrong. You can also call prompt interactively, errors should be displayed to the screen when you do that.

You can debug your prompt by setting a breakpoint:

Set-BreakPoint -Command Prompt

Then you can step through and see what's going wrong.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top