Skip to content

Instantly share code, notes, and snippets.

@compwiz32
Last active November 19, 2022 05:26
Show Gist options
  • Save compwiz32/cde6f25f9a813e45884df61fec71cc72 to your computer and use it in GitHub Desktop.
Save compwiz32/cde6f25f9a813e45884df61fec71cc72 to your computer and use it in GitHub Desktop.
Script for article - "Customize your PowerShell commnd prompt"
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 ($(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
@compwiz32
Copy link
Author

Want to know how I made this script? Read about it here: https://www.networkadm.in/customize-pscmdprompt/

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