Power Shell | Working with Aliases

Related CommandLets

  • Get-Alias
  • New-Alias
  • Set-Alias
  • Export-Alias
  • Import-Alias 

Display Aliases

Show Aliases

Get-Alias

Show Aliases for a Command

Get-Alias -Definition Get-ChildItem

Export the entire list to a spreadsheet (a CSV file) by using the Export-Alias:

Export-Alias -Path "Alias.csv"

Show only build-in aliases (with property read-only)

Get-Alias | Where-Object {$_.Options -Match "ReadOnly"}

Create Alias

New-Alias -Name D -Value Get-ChildItem -Description "A shortcut to the Get-ChildItem cmdlet"

Create a shortcut ‘c’ for Visual Studio Code ‘code’

Set-Alias -Name c -Value code  

Create more complex aliases using functions

function Start-TheDay {
    start chrome;
    start firefox;
    start code;
    start slack;
}

Set-Alias -Name am -Value Start-TheDay  

Customize prompt

Microsoft Powershell Core – About Prompts

function Prompt(){
   $W = Split-Path -leaf -path (Get-Location)
   $prompt = Write-Prompt "$($env:UserName)@$($env:ComputerName):" -ForegroundColor Green
   $prompt += Write-Prompt $W -ForegroundColor DarkCyan
   $prompt += Write-Prompt '>'
   
   return ' '
}

Get code that sets the prompt

(Get-Command Prompt).ScriptBlock

Samples

function prompt {"PS [$env:COMPUTERNAME]> "}
function prompt {"$(Get-Date)> "}
function prompt {
  $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
  $principal = [Security.Principal.WindowsPrincipal] $identity
  $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator

  $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
    elseif($principal.IsInRole($adminRole)) { "[ADMIN]: " }
    else { '' }
  ) + 'PS ' + $(Get-Location) +
    $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}
function prompt {
   # The at sign creates an array in case only one history item exists.
   $history = @(Get-History)
   if($history.Count -gt 0)
   {
      $lastItem = $history[$history.Count - 1]
      $lastId = $lastItem.Id
   }

   $nextCommand = $lastId + 1
   $currentDirectory = Get-Location
   "PS: $nextCommand $currentDirectory >"
}
function prompt {
    $color = Get-Random -Min 1 -Max 16
    Write-Host ("PS " + $(Get-Location) +">") -NoNewLine `
     -ForegroundColor $Color
    return " "
}
function Prompt
{
     # Admin ?
     if( (
        New-Object Security.Principal.WindowsPrincipal (
            [Security.Principal.WindowsIdentity]::GetCurrent())
        ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    {
        # Admin-mark in WindowTitle
        $Host.UI.RawUI.WindowTitle = "[Admin] " + $Host.UI.RawUI.WindowTitlep
        # Admin-mark on prompt
        Write-Host "[" -nonewline -foregroundcolor DarkGray
        Write-Host "Admin" -nonewline -foregroundcolor Red
        Write-Host "] " -nonewline -foregroundcolor DarkGray
    }   
    Write-Host "[" -NoNewline
    Write-Host (Get-Date -Format "HH:mm:ss") -ForegroundColor Gray -NoNewline
    Write-Host "] [" -NoNewline    
    Write-Host "$(((H)[-1].EndExecutionTime - (H)[-1].StartExecutionTime).Milliseconds) ms" -NoNewline -ForegroundColor Gray
    Write-Host "]" -NoNewline
    if(Get-Module Posh-git) {Write-VcsStatus; Write-host ''}
    Write-Host "$($executionContext.SessionState.Path.CurrentLocation.ProviderPath)" -NoNewline
    "> "
}

Docker Aliases

drm

Removes all stopped containers:

function Remove-StoppedContainers {  
    docker container rm $(docker container ls -q)
}
Set-Alias drm  Remove-StoppedContainers  

drmf

Removes all containers, whether they’re running or not:

function Remove-AllContainers {  
    docker container rm -f $(docker container ls -aq)
}
Set-Alias drmf  Remove-AllContainers  

Use with caution

dip

Gets the container’s IP address – pass it a container name or part of the container ID, e.g. dip 02a or dip dbserver:

function Get-ContainerIPAddress {  
    param (
        [string] $id
    )
    & docker inspect --format '{{ .NetworkSettings.Networks.nat.IPAddress }}' $id
}
Set-Alias dip  Get-ContainerIPAddress  

d2h

Adds a container’s IP address to the host’s hosts file, so you can refer to containers by their name on your Docker host, in the same way that containers reach each other by name.

Example – I have a web app which uses a SQL database. In dev and test environments I’ll be running SQL Server in a container for the database. The container is called petshop-db and all the connection strings in the web configuration use petshop-db as the database server name. If I want to run the web app locally, but still use a container for the database I just start the container and run d2h petshop-db. Now my web app uses the container IP from the hosts file, and I can run the whole stack with docker-compose up without changing config.

function Add-ContainerIpToHosts {  
    param (
        [string] $name
    )
    $ip = docker inspect --format '{{ .NetworkSettings.Networks.nat.IPAddress }}' $name
    $newEntry = "$ip  $name  #added by d2h# `r`n"
    $path = 'C:WindowsSystem32driversetchosts'
    $newEntry + (Get-Content $path -Raw) | Set-Content $path
}
Set-Alias d2h  Add-ContainerIpToHosts  

Network Aliases

List Jobs for Port

function List-Jobs-Using-Port {  
    param (
        [string] $port
    )

    Get-Process -Id (Get-NetTCPConnection -LocalPort $port).OwningProcess
}

Top Ten Aliases

Guy’s Top Ten Aliases

  1. Cd: Set-Location
  2. Cls: Clear-Host
  3. Del: Remove-Item
  4. Diff: Compare-Object
  5. Dir: Get-ChildItem
  6. Kill: Stop-Process
  7. Echo: Write-Output
  8. Sort: Sort-Object
  9. Sleep: Start-Sleep
  10. Type: Get-Content

List of Aliases

More to read

https://stackify.com/powershell-commands-every-developer-should-know/

References and Copyright

Aliases and Prompts

https://gist.github.com/sixeyed/c3ae1fd8033b8208ad29458a56856e05

Copyright © 2024 | Powered by WordPress | Aasta Blog theme by ThemeArile
NameDefinition
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Performance
Analytics
Advertisement
Others