I keep hearing from new users who are used to bash-style aliases, how frustrating it is not to be able to create aliases with parameters, the way you can in bash …

I’m going to show you how to make the “alias” command work roughly the way it does in bash, but first, let me clear this up:

Bash or Csh PowerShell
script script
alias, shell functions function
... alias

In Bash, the recommendation is that “for almost every purpose, shell functions are preferred over aliases” ... and that recommendation is even stronger for PowerShell. The PowerShell “alias” is a true alias — it’s just another name for a command, script, function, etc. and it doesn’t support passing parameters or making mini-scripts at all.

Usually, an alias serves to give you a name you can remember, but sometimes it’s just to shorten the name, . Another use for them is to let you specify the default cmdlet — if you have two cmdlets (or script functions) with the same name, you can use an alias to override which one is executed by default.

The PowerShell function can do everything a bash alias can do (and everything a function or script can do, but this isn’t a tip about that, it’s a tip about making an alias [new] and unalias command that works the way you expect it to). So …


## Aliases.ps1 -- to be dot-sourced from your profile
if($Host.Version.Major -ge 2) {
   function script:Resolve-Aliases
   {
      param($line)

      [System.Management.Automation.PSParser]::Tokenize($line,[ref]$null) | % {
         if($_.Type -eq "Command") {
            $cmd = @(which $_.Content)[0]
            if($cmd.CommandType -eq "Alias") {
               $line = $line.Remove( $_.StartColumn -1, $_.Length ).Insert( $_.StartColumn -1, $cmd.Definition )
            }
         }
      }
      $line
   }
}

function alias {
   # pull together all the args and then split on =
   $alias,$cmd = [string]::join(" ",$args).split("=",2) | % { $_.trim()}

   if($Host.Version.Major -ge 2) {
      $cmd = Resolve-Aliases $cmd
   }
   New-Item -Path function: -Name "Global:Alias$Alias" -Options "AllScope" -Value @"
Invoke-Expression '$cmd `$args'
###ALIAS###
"@


   Set-Alias -Name $Alias -Value "Alias$Alias" -Description "A UNIX-style alias using functions" -Option "AllScope" -scope Global -passThru
}

function unalias([string]$Alias,[switch]$Force){
   if( (Get-Alias $Alias).Description -eq "A UNIX-style alias using functions" ) {
      Remove-Item "function:Alias$Alias" -Force:$Force
      Remove-Item "alias:$alias" -Force:$Force
      if($?) {
         "Removed alias '$Alias' and accompanying function"
      }
   } else {
      Remove-Item "alias:$alias" -Force:$Force
      if($?) {
         "Removed alias '$Alias'"
      }
   }
}
 

You can save that as alias.ps1 and create your aliases the way you used to in bash alias ls='ls -recurse' and still be able to invoke them and, you can pass them extra parameters somewhat like in csh when you invoke them. :-) I’ve added some extra text in the function name and content and in the alias description, so it’s actually pretty easy to find all the aliases and functions this script creates and dump them to a file so you can reload them later if you want … but I haven’t actually written a function to do that yet myself.

One important note: You must not use recursive aliases in the bindings on v1 — that is, alias ls='ls -recurse' will loop until it hits PowerShell’s recursive limit (only 100) and exit if you try to use it on v1 — because the script won’t be able to resolve the alias “ls” to Get-ChildItem … you’re probably better off not relying on that feature anyway.

This is the second in an occasional series of tips for PowerShell users: short posts which don’t intend to give guidance, but merely a tip on a feature you may not be aware of, or maybe even answers to some of the recurring questions that come up in #PowerShell.

Fixing the “Current Directory” problem

The core of this tip is very simple: Windows tracks your application’s “current directory” ... and you can get and set this location using static methods of the System.IO.Directory class: SetCurrentDirectory and GetCurrentDirectory.

The reason this is showing up as a Power User Tip is that PowerShell doesn’t set this environment setting when you navigate — it uses it’s internal “PSProvider” architecture, and doesn’t differentiate between whether you’re in a FileSystem location or a registry location, or even a third-party provider. So, it never actually changes the current directory, and any console command or .net method you call which uses the current directory will most likely be in the wrong place — like, for instance:


$sw = New-Object System.IO.StreamWriter("NeatFile.txt")
$sw.writeline("I could write a lot of neat stuff here!")
$sw.close()
 

The problem is that now you don’t know where “NeatFile.txt” is — the “current directory” depends on how you launched PowerShell — most frequently it’s your $Home directory (equivalent to Env:HOMEDRIVE + Env:HOMEPATH — usually something like C:\Documents and Settings\YourName), but it could be your SystemRoot (C:\Windows) or the current directory of the app that launched PowerShell (eg: C:\Windows\System32 when you run it via “runas”). You can figure it out by running: [IO.Directory]::GetCurrentDirectory().

But here’s something more interesting: you can “fix” the problem by using [IO.Directory]::SetCurrentDirectory. There are a couple of catches, however: You can’t just use $pwd or Get-Location because you might be in the registry or some other location that’s not a Directory. And you can’t just use Get-Location -PSProvider FileSystem because even though it returns the current FileSystem provider path, the FileSystem provider supports “fake” PSDrives (eg: you could create a Scripts: drive like new-psdrive scripts filesystem "$Home\Scripts") and these aren’t actually supported by the .Net FileSystem. Luckily, PowerShell includes a Convert-Path cmdlet which was created for this very purpose: converting a path from a Windows PowerShell path to a native path supported by the underlying provider.

Without further ado, here’s a one-liner you can add to your prompt function:


[IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location -PSProvider FileSystem)))
 

[new] Edit: You can do the same thing using the System.Environment class, and it turns out that the ProviderPath is a property of the PathInfo object, perhaps you’ll find this syntax simpler:


[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
 

This is the first in what I hope will be an occasional series of tips for PowerShell users: short posts which don’t intend to give guidance, but merely a tip on a feature you may not be aware of, or maybe even answers to some of the recurring questions that come up in #PowerShell. We’ll see how this goes …

My first tip to power users is to remember the priority which PowerShell assigns to things by default:
  1. Alias
  2. Function (and Filter)
  3. Cmdlet
  4. ExternalScript
  5. Application
  6. Files with associations

This means that using an Alias, you can override anything (and since you can’t have multiple aliases with the same name, that makes aliases the ultimate way to disambiguate commands).

Functions and filters (there’s really no such thing as a filter) come before cmdlets (yes, even built-in cmdlets) and scripts (that is, your .ps1 files which are in your path, and are called “ExternalScripts” by PowerShell) come before applications, which come before scripts written in other languages, like .vbs or .bat or .cmd (even though they’re all shown as “Application” type commands, PowerShell prioritizes apps over executable scripts which are associated with an engine).

Incidentally, I’m not actually sure what a “Script” is (it’s a CommandType for Get-Command, but there aren’t any on my PCs) if anyone can run get-command -type "Script" and get something output, please let me know what it was.

It’s important to understand that this precedence order is not what you get if you run Get-Command (Get-Command merely orders everything alphabetically by name). In fact, as far as I know, PowerShell doesn’t give you a way to get a list of commands in the order that they would execute, nor does it specify any way of determining that order in the documentation. If you would like to see the proper order, you could use the following “filter” function, and sort by Order bearing in mind that it really only works precisely when you type the full command without wildcards. ;-)


filter which {
   $_.Order = "luimcxp".IndexOf( $($_.CommandType)[1] )
   $_
}

# So then you can pipe through which, and sort by order:
Get-Command SomeCommand | which | sort order

 

Oh, by the way, in case it’s not obvious … “luimcxp” is the second letter of each “CommandType” (which is unique in each one) in the order that I think they belong in … so IndexOf( $($_.CommandType)[1] ) gives us the correct ordering for the command in $_.