在 PowerShell 中 cd 至,cd 加 ls

问题描述 投票:0回答:2

如何在 PowerShell 中编写函数或命令的别名,以便 cd 可以做两件事:

  1. cd 给定的目录
  2. 是目录内容

编辑:

我需要的是这个:

function ccd
{
    param($path)
    set-location $path 
    ls
}

但我想写cd而不是ccd。当我将函数名称更改为 cd (从 ccd)时,它会更改目录,但不会列出其中的项目:(。似乎我的 cd 函数被覆盖。

shell powershell scripting
2个回答
7
投票

你的意思是这样的吗?

function Set-LocationWithGCI{
    param(
            $path
         )
    if(Test-Path $path){
        $path = Resolve-Path $path
        Set-Location $path
        Get-ChildItem $path
    }else{
        "Could not find path $path"
    }
}
Set-Alias cdd Set-LocationWithGCI -Force

我发现您实际上想更改内置的 cd 别名。为此,您需要删除现有的,然后创建新的:

Remove-Item alias:\cd
New-Alias cd Set-LocationWithGCI

0
投票

我会在这里添加我的两分钱,为了未来的我,以防万一有人感兴趣。

在 my_profile.ps1 中:

function Set-LocationAndShowDir{
    param($path)
    try {
      Set-Location $path -ErrorAction Stop
      Get-ChildItem
    } catch {
      Write-Error $_
    }
}
Remove-Alias cd
Set-Alias cd Set-LocationAndShowDir -Force

这受到@ebgreen答案的启发,但在失败的情况下会显示原始错误,感觉更透明。

© www.soinside.com 2019 - 2024. All rights reserved.