1

I am trying to customize my PS Prompt in Windows 10 by adding the Azure Account ID. However, it is not working as expected.

Output of Azure Account ID, results in the following:

[0.04 sec] > (Get-AzContext).Account.Id
david.maryo@jd.com

I want the my result 'Account.Id' from the above command should be displayed in my PS Prompt. But it is not displaying the necessary results. Please refer the below screenshot for information.

Screenshot of the Current PS Prompt: enter image description here

Microsoft.PowerShell_profile.ps1

function prompt {  
    #Assign Windows Title Text
    $host.ui.RawUI.WindowTitle = "Current Folder: $pwd"

    #Configure current user, current folder and date outputs
    $CmdPromptCurrentFolder = Split-Path -Path $pwd -Leaf
    $CmdPromptUser = [Security.Principal.WindowsIdentity]::GetCurrent();
    $Date = Get-Date -Format 'dddd hh:mm:ss tt'

    # Test for Admin / Elevated
    $IsAdmin = (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)

    #Calculate execution time of last cmd and convert to milliseconds, seconds or minutes
    $LastCommand = Get-History -Count 1
    if ($lastCommand) { $RunTime = ($lastCommand.EndExecutionTime - $lastCommand.StartExecutionTime).TotalSeconds }

    if ($RunTime -ge 60) {
        $ts = [timespan]::fromseconds($RunTime)
        $min, $sec = ($ts.ToString("mm\:ss")).Split(":")
        $ElapsedTime = -join ($min, " min ", $sec, " sec")
    }
    else {
        $ElapsedTime = [math]::Round(($RunTime), 2)
        $ElapsedTime = -join (($ElapsedTime.ToString()), " sec")
    }

    #Decorate the CMD Prompt
    Write-Host ""
    Write-Host "Azure: (Get-AzContext).Account.Id"
    Write-host ($(if ($IsAdmin) { 'Elevated ' } else { '' })) -BackgroundColor DarkRed -ForegroundColor White -NoNewline
    Write-Host " USER:$($CmdPromptUser.Name.split("\")[1]) " -BackgroundColor DarkBlue -ForegroundColor White -NoNewline
    If ($CmdPromptCurrentFolder -like "*:*")
        {Write-Host " $CmdPromptCurrentFolder "  -ForegroundColor White -BackgroundColor DarkGray -NoNewline}
        else {Write-Host ".\$CmdPromptCurrentFolder\ "  -ForegroundColor White -BackgroundColor DarkGray -NoNewline}

    Write-Host " $date " -ForegroundColor White
    Write-Host "[$elapsedTime] " -NoNewline -ForegroundColor Green
    return "> "
} #end prompt function
Maryo David
  • 539
  • 1
  • 7
  • 18
  • 1
    Just for my understanding: You expect that `Write-Host "Azure: (Get-AzContext).Account.Id"` prints out something other than the actual string `"Azure: (Get-AzContext).Account.Id"`? – Tomalak Mar 06 '22 at 14:30
  • 1
    Or asked the other way around, what does `Write-Host "Azure:" (Get-AzContext).Account.Id` print? – Tomalak Mar 06 '22 at 14:31

1 Answers1

3

Tomalak is hinting at the problem in a comment (and shows an alternative solution), but let me spell it out:

In order:

Write-Host "Azure: $((Get-AzContext).Account.Id)"

See this answer for a comprehensive overview of PowerShell's expandable strings (string interpolation).

In general, only the following characters are metacharacters inside "..." - all others are treated as literals (which explains why you saw verbatim (Get-AzContext).Account.Id) in your prompt string):

  • ` (backtick) PowerShell's escape character - see the conceptual about_Special_Characters help topic.

    • If doubled, also ": "" escapes a single " and is equivalent to `"
  • $, the start of a variable reference (e.g., $HOME) or subexpression ($(...), as above).


For the sake of completeness, here are alternative solutions:

# String concatenation - the expression must be enclosed in (...)
Write-Host ('Azure: ' + (Get-AzContext).Account.Id)

# The -f (string-formatting operator)
Write-Host ('Azure: {0}' -f (Get-AzContext).Account.Id)

# Tomalak's alternative, which relies on Write-Host space-concatenating
# its individual arguments.
# Note how a single expression can act as a command argument as-is.
Write-Host 'Azure:' (Get-AzContext).Account.Id
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thanks for the pointers. It worked as you suggested. I wanted that output to be printed before 'Elevated' with some background/foreground colors. Is that possible? Currently its getting printed separately in the first line.. – Maryo David Mar 06 '22 at 15:15
  • @MaryoDavid, to make [`Write-Host`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-host) not print a trailing newline, use `-NoNewLine`. To use colors, use `-ForegroundColor` and `-BackgroundColor`. In PowerShell (Core) 7+ you can alternatively embed ANSI escape sequences in your strings. If you need further assistance, please ask a _new_ question. Given that this answer addresses your question as asked, please consider accepting it. – mklement0 Mar 06 '22 at 16:01