4

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?

Brian Cross
  • 142
  • 1
  • 7
  • You want to change what `ls` does without changing what `ls` does? – TessellatingHeckler Apr 17 '18 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. – Jeff Zeitlin Apr 17 '18 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. – Brian Cross Apr 17 '18 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`. – lit Apr 17 '18 at 22:42

1 Answers1

6

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.

Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
  • 2
    How would that function be used? Remember people coming here are refugees from Unix or something and know little about PowerShell conventions. – MarkHu Apr 18 '19 at 23:02
  • How to use a function? Type its name at the PowerShell command prompt and hit `Enter`. – Bill_Stewart Apr 23 '19 at 21:50
  • I was curious where to define a function, i.e. https://stackoverflow.com/questions/52175669/is-there-a-windows-10-powershell-equivalent-to-bashrc-for-linux-bash and/or https://superuser.com/questions/1268727/powershell-profile-does-not-load – MarkHu Apr 24 '19 at 15:29
  • 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. – Bill_Stewart Apr 24 '19 at 17:18