如何找出递归操作工作的确切位置?



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

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

对于低于"深度 0"一级的文件夹中的文件,用于替换的字符串需要以../a>../stylesheet.css为前缀。

对于低于"深度 0"两级的文件夹中的文件,用于替换的字符串需要以../为前缀两次 ->../../stylesheet.css。 ...等等...

我被困在这里:

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

我需要$depth才能包含根$path下的文件夹数量。

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

$thisLocation = Get-Location
$path = Join-Path -path $thisLocation -childpath "Filesdepth0"
$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
}

这是我编写的一个函数,它使用递归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:SomeExamplePath'
Get-PathDepth -Path $MyPath

返回 3。

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

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

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

New-Item -Path "C:LogsOnceTest.txt" -Force
New-Item -Path "C:LogsTwiceFolder_In_TwiceTest.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:LogsOnceTest.txt -- Depth is 4
C:LogsTwiceFolder_In_TwiceTest.txt -- Depth is 5

最新更新