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

NameDefinition
%Foreach-Object
?Where-Object
acAdd-Content
asnpAdd-PSSnapIn
catGet-Content
cdSet-Location
chdirSet-Location
clcClear-Content
clearClear-Host
clhyClear-History
cliClear-Item
clpClear-ItemProperty
clsClear-Host
clvClear-Variable
compareCompare-Object
copyCopy-Item
cpCopy-Item
cpiCopy-Item
cppCopy-ItemProperty
cvpaConvert-Path
dbpDisable-PSBreakpoint
delRemove-Item
diffCompare-Object
dirGet-ChildItem
ebpEnable-PSBreakpoint
echoWrite-Output
epalExport-Alias
epcsvExport-Csv
epsnExport-PSSession
eraseRemove-Item
etsnEnter-PSSession
exsnExit-PSSession
fcFormat-Custom
flFormat-List
foreachForeach-Object
ftFormat-Table
fwFormat-Wide
galGet-Alias
gbpGet-PSBreakpoint
gcGet-Content
gciGet-ChildItem
gcmGet-Command
gcsGet-PSCallStack
gdrGet-PSDrive
ghyGet-History
giGet-Item
gjbGet-Job
glGet-Location
gmGet-Member
gmoGet-Module
gpGet-ItemProperty
gpsGet-Process
groupGroup-Object
gsnGet-PSSession
gsnpGet-PSSnapIn
gsvGet-Service
guGet-Unique
gvGet-Variable
gwmiGet-WmiObject
hGet-History
historyGet-History
icmInvoke-Command
iexInvoke-Expression
ihInvoke-History
iiInvoke-Item
ipalImport-Alias
ipcsvImport-Csv
ipmoImport-Module
ipsnImport-PSSession
isepowershell_ise.exe
iwmiInvoke-WMIMethod
killStop-Process
lpOut-Printer
lsGet-ChildItem
manhelp
mdmkdir
measureMeasure-Object
miMove-Item
mountNew-PSDrive
moveMove-Item
mpMove-ItemProperty
mvMove-Item
nalNew-Alias
ndrNew-PSDrive
niNew-Item
nmoNew-Module
nsnNew-PSSession
nvNew-Variable
ogvOut-GridView
ohOut-Host
popdPop-Location
psGet-Process
pushdPush-Location
pwdGet-Location
rInvoke-History
rbpRemove-Breakpoint
rcjbReceive-Job
rdRemove-Item
rdrRemove-PSDrive
renRename-Item
rjbRemove-Job
rmRemove-Item
rmdirRemove-Item
rmoRemove-Module
rniRename-Item
rnpRename-ItemProperty
rpRemove-ItemProperty
rsnRemove-PSSession
rsnpRemove-PSSnapin
rvRemove-Variable
rvpaResolve-Path
rwmiRemove-WMIObject
sajbStart-Job
salSet-Alias
sapsStart-Process
sasvStart-Service
sbpSet-PSBreakpoint
scSet-Content
selectSelect-Object
setSet-Variable
siSet-Item
slSet-Location
sleepStart-Sleep
sortSort-Object
spSet-Property
spcbStop-Job
sppsStop-Process
spsvStop-Service
startStart-Process
svSet-Variable
swmiSet-WMIInstance
teeTee-Object
typeGet-Content
whereWhere-Object
wjbWait-Job
writeWrite-Output

More to read

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

References and Copyright

Aliases and Prompts

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

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

de German
X