【问题标题】:How to supply argument to value of New-Alias command?如何为 New-Alias 命令的值提供参数?
【发布时间】:2017-02-08 17:46:15
【问题描述】:

我希望Get-ChildItem -force 在我输入ll 时被执行,我的profile.ps1 中有这个:

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

但是,当我输入 ll 时,我可以看到 -force 参数没有被使用。我做错了什么?

编辑:我真正希望实现的是显示文件夹中的所有文件,即使它们是隐藏的。我希望将此绑定到ll

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你不能用别名做到这一点。别名实际上只是命令的不同名称,它们不能包含参数。

    然而,您可以做的是编写一个函数而不是使用别名:

    function ll {
      Get-ChildItem -Force @args
    }
    

    但是,在这种情况下,您不会获得参数的制表符补全,因为该函数不会通告任何参数(即使 Get-ChildItem 的所有参数都通过并工作)。您可以通过有效地为函数复制 Get-ChildItem 的所有参数来解决这个问题,类似于 PowerShell 自己的 help 函数的编写方式(您可以通过 Get-Content Function:help 检查其源代码)。

    【讨论】:

      【解决方案2】:

      要添加到Joey's excellent answer,这是how you can generateGet-ChildItem 的代理命令(不包括特定于提供程序的参数):

      # 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))
      

      【讨论】:

        猜你喜欢
        • 2012-08-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2011-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多