代码之家  ›  专栏  ›  技术社区  ›  Rakha

获取给定文件的第二个父目录

  •  -1
  • Rakha  · 技术社区  · 7 年前

    我有一个脚本,可以找到包含特定字符串的文件。

    假设我找到的文件是:

    C:\temp\drivers\etc\file.INF
    

    我要获取该文件的第二个父文件夹。

    例如,如果是:

    C:\temp\drivers\etc\file.inf文件
    

    我想走这条路:

    C:\temp\drivers
    

    在这种情况下,什么对你最有意义?

    我可以让它工作:

    $test = "C:\temp\drivers\etc\file.INF" 
    $first_parent = Split-path $test -Parent
    $second_parent= $first_parent.Substring(0,$first_parent.LastIndexOf('\'))
    $second_parent
    

    输出:

    C:\临时\驱动程序
    

    但它是最优的吗?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Lee_Dailey    7 年前

    如果您的项是一个文件(而不仅仅是字符串),则可以从 fileinfo 从中获取的对象 Get-Item Get-ChildItem 是的。这样地。。。

    $FileName_String = 'C:\temp\drivers\etc\file.INF'
    # fake reading in the fileinfo object
    #    in real life, use Get-Item or Get-ChildItem
    $FileName_FileInfoObject = [System.IO.FileInfo]$FileName_String
    
    $2ndParentDir = $FileName_FileInfoObject.Directory.Parent
    
    $FileName_String
    $FileName_FileInfoObject.FullName
    $2ndParentDir.FullName
    

    输出…

    C:\temp\drivers\etc\file.INF
    C:\temp\drivers\etc\file.INF
    C:\temp\drivers
    

    如果它只是一个字符串,那么您需要使用 Split-Path 两次。[ 咧嘴笑 ]

        2
  •  0
  •   Rakha    7 年前

    使用分割路径两次就可以完成。最简单的方法是用管道:

    $test = "C:\temp\drivers\etc\file.INF"
    Split-path $test | split-path 
    

    输出:

    C:\temp\drivers