You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中实现Linux ls -d的目录列出功能

实现类似Linux ls -d 的目录列表效果

我需要列出文件中指定的已存在目录,但不遍历其内部子目录。当前执行命令后会递归显示子目录,同时希望保留不存在路径的错误提示。

当前命令及问题输出

PS C:\Users\myHomeDIR> cat .\toto.txt
.\.config
C:\DA FI
PS C:\Users\myHomeDIR> cat .\toto.txt | dir | % FullName
C:\Users\myHomeDIR\.config\scoop
dir : Cannot find path 'C:\DA FI' because it does not exist.
At line:1 char:18
+ cat .\toto.txt | dir | % FullName
+                  ~~~
    + CategoryInfo          : ObjectNotFound: (C:\DA FI:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

PS C:\Users\myHomeDIR> 

期望效果

仅显示存在的目录本身,不展开子目录,同时保留不存在路径的错误提示:

C:\Users\myHomeDIR\.config
dir : Cannot find path 'C:\DA FI' because it does not exist.
At line:1 char:18
+ cat .\toto.txt | dir | % FullName
+                  ~~~
    + CategoryInfo          : ObjectNotFound: (C:\DA FI:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

解决方法

方法一:逐个处理路径并自定义错误输出

Get-Content .\toto.txt | ForEach-Object {
    $dir = Get-ChildItem -Path $_ -Directory -ErrorAction SilentlyContinue
    if ($dir) {
        $dir.FullName
    } else {
        Write-Error "Cannot find path '$_' because it does not exist." -Category ObjectNotFound
    }
}

方法二:简洁管道写法

利用-ErrorAction Continue保留错误提示,-Directory限定只匹配目录:

Get-Content .\toto.txt | ForEach-Object {
    Get-ChildItem -LiteralPath $_ -Directory -ErrorAction Continue | Select-Object -ExpandProperty FullName
}

参数说明

  • -Directory:仅匹配目录类型的项目,排除文件
  • -LiteralPath:严格解析输入的路径字符串,避免空格等特殊字符被误处理
  • -ErrorAction Continue:遇到错误时输出提示信息,同时继续处理后续路径

内容的提问来源于stack exchange,提问作者SebMa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 15:01:17