5

This may be some simple solution I am missing. I would like to alias the command line:

> ls -lrt

To actually do this:

> Get-ChildItem | Sort-Object -Property LastWriteTime

The issue I see is that the ls is already aliased to Get-Children and that resolved prior to any attemps I have made such as:

New-Alias -Name 'ls -lrt' -Value 'Get-ChildItem | Sort-Object -Property LastWriteTime'

Does anyone know a way to do this without harming the previously existing alias of ls?

4
  • You want to change what ls does without changing what ls does? Commented Apr 17, 2018 at 18:54
  • Unlike in bash, PowerShell aliases can't inherently include parameters. Instead, you'll have to write a function which takes the parameters you want, and does what you want with them. However, PowerShell is not bash, and you should not get into the habit of duplicating bash commands exactly - the aliases were provided as a 'crutch' for certain common commands while you familiarize yourself with PowerShell's way of doing things. Commented Apr 17, 2018 at 18:54
  • I understand jeff. It is just a long command to type and my muscle memory for ls -lrt is hitting the enter even before my brain engages. So many times I have so much in a folder that this command is invaluable. Commented Apr 17, 2018 at 18:56
  • The PowerShell aliases, such as ls, are not enjoyed by all. The theory is that they will make someone new to PowerShell feel more comfortable and more accepting. This breaks down whenever someone tries anything past the most simplistic command when they find out that ls does not do what ls does. Those coming from Windows feel the same way about dir. Commented Apr 17, 2018 at 22:42

1 Answer 1

7

Aliases don't support parameters. What you actually want is a function:

function ls {
  param(
    [Switch] $lrt
  )
  if ( $lrt ) {
    Get-ChildItem | Sort-Object LastWriteTime
  }
  else {
    Get-ChildItem $args
  }
}

You will need to remove the ls alias in this case, and use the function instead.

Sign up to request clarification or add additional context in comments.

4 Comments

How would that function be used? Remember people coming here are refugees from Unix or something and know little about PowerShell conventions.
How to use a function? Type its name at the PowerShell command prompt and hit Enter.
I was curious where to define a function, i.e. stackoverflow.com/questions/52175669/… and/or superuser.com/questions/1268727/…
I would start with the help - run help about_Functions at a PowerShell prompt - and read on. PowerShell's help is really quite good, and there is a lot of helpful information therein.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.