我怎样才能找到递归操作的确切位置?

How can I find out the exact location where the recursive operation is working?

我的问题是,替换字符串需要根据指定文件所在的文件夹深度进行更改,我不知道如何获取该信息。我需要使用相对地址。

我希望脚本 运行 来自所有需要更正的文件的文件夹上方的 2 个文件夹级别。所以我在第 1 行设置了 $path。该文件夹假设为 'depth 0'。在这里,替换字符串需要采用其原始形式 -> stylesheet.css.

对于'depth 0'下一级文件夹中的文件,替换字符串需要加上../一次前缀-> ../stylesheet.css.

对于 'depth 0' 下两级文件夹中的文件,替换字符串需要加上两次 ../ 前缀 -> ../../stylesheet.css。 ...等等...

我被困在这里:

$depth = $file.getDepth($path) #> totally clueless here

我需要$depth来包含根目录下的文件夹数量$path

我怎样才能得到这个?这是我的其余代码:

$thisLocation = Get-Location
$path = Join-Path -path $thisLocation -childpath "\Files\depth0"
$match = "findThisInFiles"
$fragment = "stylesheet.css" #> string to be prefixed n times
$prefix = "../" #> prefix n times according to folder depth starting at $path (depth 0 -> don't prefix)
$replace = "" #> this will replace $match in files
$depth = 0

$htmlFiles = Get-ChildItem $path -Filter index*.html -recurse

foreach ($file in $htmlFiles)
{
    $depth = $file.getDepth($path) #> totally clueless here
    $replace = ""
    for ($i=0; $i -lt $depth; $i++){
        $replace = $replace + $prefix
    }
    $replace = $replace + $fragment

    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace $match, $replace } |
    Set-Content $file.PSPath
}

这是一种获取某个位置中所有文件的文件夹结构深度的方法。希望这可以帮助您朝着正确的方向前进

New-Item -Path "C:\Logs\Once\Test.txt" -Force
New-Item -Path "C:\Logs\Twice\Folder_In_Twice\Test.txt" -Force

$Files = Get-ChildItem -Path "C:\Logs\" -Recurse -Include *.* | Select-Object FullName

foreach ($File in $Files) {
    [System.Collections.ArrayList]$Split_File = $File.FullName -split "\"
    Write-Output ($File.FullName + " -- Depth is " + $Split_File.Count)
}

输出只是为了说明

C:\Logs\Once\Test.txt -- Depth is 4
C:\Logs\Twice\Folder_In_Twice\Test.txt -- Depth is 5

这是我编写的一个函数,它使用 Split-Path 递归地确定路径的深度:

Function Get-PathDepth ($Path) {
    $Depth = 0
    While ($Path) {
        Try {
            $Parent = $Path | Split-Path -Parent
        }
        Catch {}

        if ($Parent) {
            $Depth++
            $Path = $Parent
        }
        else {
            Break
        }
    }
    Return $Depth
}

用法示例:

$MyPath = 'C:\Some\Example\Path'

Get-PathDepth -Path $MyPath

Returns3.

不幸的是,我不得不将 Split-Path 包装在 Try..Catch 中,因为如果您将根路径传递给它,则会引发错误。这很不幸,因为这意味着真正的错误不会导致异常发生,但目前看不到解决方法。

使用 Split-Path 的优点是无论是否使用尾随 \,您都应该获得一致的计数。