Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to supply argument to value of New-Alias command?

Tags:

powershell

I wish Get-ChildItem -force to get executed when I type ll and I have this in my profile.ps1:

New-Alias -Name ll -Value Get-ChildItem -force

However, when I type ll, I can see that the -force argument is not being used. What am I doing wrong?

Edit: What I really wish to achieve is to show all files in a folder, even if they're hidden. And I wish to bind this to ll.

like image 927
fredrik Avatar asked Feb 06 '23 03:02

fredrik


2 Answers

You cannot do that with aliases. Aliases are really just different names for commands, they cannot include arguments.

What you can do, however, is, write a function instead of using an alias:

function ll {
  Get-ChildItem -Force @args
}

You won't get tab completion for arguments in that case, though, as the function doesn't advertise any parameters (even though all parameters of Get-ChildItem get passed through and work). You can solve that by effectively replicating all parameters of Get-ChildItem for the function, akin to how PowerShell's own help function is written (you can examine its source code via Get-Content Function:help).

like image 139
Joey Avatar answered Feb 15 '23 09:02

Joey


To add to Joey's excellent answer, this is how you can generate a proxy command for Get-ChildItem (excluding provider-specific parameters):

# Gather CommandInfo object
$CommandInfo = Get-Command Get-ChildItem

# Generate metadata
$CommandMetadata = New-Object System.Management.Automation.CommandMetadata $CommandInfo

# Generate cmdlet binding attribute and param block
$CmdletBinding = [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($CommandMetadata)
$ParamBlock = [System.Management.Automation.ProxyCommand]::GetParamBloc($CommandMetadata)

# Register your function
$function:ll = [scriptblock]::Create(@'
  {0}
  param(
    {1}
  )

  $PSBoundParameters['Force'] = $true

  Get-ChildItem @PSBoundParameters
'@-f($CmdletBinding,$ParamBlock))
like image 37
Mathias R. Jessen Avatar answered Feb 15 '23 09:02

Mathias R. Jessen