PowerShell 递归与 Pipe 。路径意外重置为脚本位置的相对路径

PowerShell recursion with Pipe . Path unexpectedly resets to relative from the script location

这应该处理每个子文件夹。我已经在这上面花了很多时间,非常感谢帮助。

输出对我来说毫无意义


function sc_t ([Parameter(ValueFromPipeline)]$path = "") {
process {

    function sc1 ([Parameter(ValueFromPipeline)]$sub_psobject, $sub_targetPath = "") {
    process {
        
        if ($sub_psobject.PSIsContainer) {
            
            $sub_psobject.fullname
            "$sub_targetPath$($sub_psobject.PSChildName)"
            
            get-childItem -Force $sub_psobject | sc1 -sub_targetPath "$sub_targetPath$($sub_psobject.PSChildName)"
        }
        
    }
    }
    
    $psobject = get-item -Force -LiteralPath $path
    sc1 $psobject

}
}

sc_t "D:\temporal"

当我 运行 你的进程时,它会在每个子文件夹上给出错误。注意到每个 Get-ChildItem 仅使用子路径..而不是完整路径。

将您的 Get-ChildItem 行更改为使用全名...应该可以。

# instead of 
get-childItem -Force $sub_psobject | ...

# do
get-childItem -Force $sub_psobject.fullname

另外..请注意您的 sc1 函数中的第二行..会产生重复项。

"$sub_targetPath$($sub_psobject.PSChildName)"

完整代码

function sc_t ([Parameter(ValueFromPipeline)]$path = "") {
  process {
    function sc1 ([Parameter(ValueFromPipeline)]$sub_psobject, $sub_targetPath = "") {
      process {
        if ($sub_psobject.PSIsContainer) {
            $sub_psobject.fullname            
            get-childItem -Force $sub_psobject.fullname | sc1 -sub_targetPath "$sub_targetPath$($sub_psobject.PSChildName)"
        }
      }
    }
    $psobject = get-item -Force -LiteralPath $path
    sc1 $psobject
  }
}