【问题标题】:Get "parent folder + file name" from a Select-String output从 Select-String 输出中获取“父文件夹 + 文件名”
【发布时间】:2013-07-15 15:31:36
【问题描述】:

我正在编写一个简单的脚本,以递归方式列出包含单词“plugin”的文件夹“fullscreen”中的所有文件。 因为路径太长,而且没有必要,所以我决定获取文件名。 问题是所有文件都称为“index.xml”,因此获取:“包含文件夹+文件名”会非常有帮助。所以输出看起来像这样:

on\index.xml
off\index.xml

代替:

C:\this\is\a\very\long\path\fullscreen\on\index.xml
C:\this\is\a\very\long\path\fullscreen\off\index.xml

这就是我所拥有的:

dir .\fullscreen | sls plugin | foreach { write-host $($_).path }

我收到此错误:

无法将参数绑定到参数“路径”,因为它为空。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你已经接近了::-)

    dir .\fullscreen | sls plugin | foreach { write-host $_.path }
    

    这也可以:

    dir .\fullscreen | sls plugin | foreach { write-host "$($_.path)" }
    

    顺便说一句,我通常会避免使用Write-Host,除非你真的只是为了让某人看到谁坐在控制台上而显示信息。如果您稍后想将此输出捕获到变量中,则它不会按原样工作:

    $files = dir .\fullscreen | sls plugin | foreach { write-host $_.path } # doesn't work
    

    大多数情况下,您只需使用标准输出流即可实现相同的输出并启用对变量的捕获,例如:

    dir .\fullscreen | sls plugin | foreach { $_.path }
    

    如果您使用的是 PowerShell v3,您可以简化为:

    dir .\fullscreen | sls plugin | % Path
    

    更新:要仅获取包含的文件夹名称,请执行以下操作:

    dir .\fullscreen | sls plugin | % {"$(split-path (split-path $_ -parent) -leaf)\$($_.Filename)"}
    

    【讨论】:

    • 感谢您的帮助,但我认为您还没有理解我想要实现的目标。我已经编辑了我的问题,提供了有关我正在寻找的输出类型的更多详细信息。干杯
    【解决方案2】:

    FileInfo 类的Directory 属性告诉你父目录,你只需要抓住它的基础并加入你的文件名。请注意将项目重新转换为 FileInfo 对象的额外 foreach:

    dir .\fullscreen | sls plugin | foreach{ get-item $_.Path } | foreach { write-output (join-path $_.Directory.BaseName $_.Name)}
    

    如果你想避免额外的管道:

    dir .\fullscreen | sls plugin | foreach{ $file = get-item $_.Path; write-output (join-path $file.Directory.BaseName $file.Name)}
    

    【讨论】:

    • Select-String 输出 MatchInfo 对象,而不是 FileInfo 对象,因此没有可用的 Directory 属性。
    • @Keith 谢谢我忘了。我编辑了我的答案以提供一种稍微不同的方法。
    • 让我们再试一次...在 PowerShell V4 中,您将能够通过 -PipelineVariable 参数(别名 pv)使用 FileInfo,例如目录 .\fullscreen -pv fi | sls 插件 | foreach { 写入输出(连接路径 $fi.Directory.BaseName $_.Filename)}
    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多