简体   繁体   English

Powershell向后爬目录树

[英]Powershell climb directory tree backwards

I have script located in C:\\projects\\bacon\\packages\\build\\run.ps1 and I am trying to locate the solution folder (in this case bacon). 我的脚本位于C:\\projects\\bacon\\packages\\build\\run.ps1 ,我试图找到解决方案文件夹(在本例中为bacon)。 Everything I've found shows how to climb forward if you know the folder name. 如果您知道文件夹名称,我发现的所有内容都会显示如何前进。 But I don't know the project name, so I need to climb backwards until I find the first containing folder that has a packages or dependencies folder within the given script's path. 但是我不知道项目名称,因此我需要向后爬,直到找到第一个包含文件夹的文件夹,该文件夹在给定脚本的路径内具有程序包或依赖项文件夹。

The closest function I've found is to use Split-Path $script:MyInvocation.MyCommand.Path to get my script's path and perhaps loop backwards somehow? 我找到的最接近的函数是使用Split-Path $script:MyInvocation.MyCommand.Path来获取脚本的路径,并可能以某种方式向后循环? but I can't find anyway of looping the folders backwards until I find the "packages" or "dependencies" folder. 但是我找不到“向后循环”文件夹,直到找到“ packages”或“ dependencies”文件夹。

You can use a combination of Get-Item and Get-ChildItem . 您可以结合使用Get-ItemGet-ChildItem Get-Item returns an object that has a Parent property. Get-Item返回具有Parent属性的对象。 You can limit Get-ChildItem to just directory objects. 您可以将Get-ChildItem限制为仅目录对象。 You can then use this to trek backwards: 然后,您可以使用此命令向后走:

$current = Get-Item .
Write-Host $Current.Parent
do
{
    $parent = Get-Item $current.Parent.FullName
    $childDirectories = $parent | Get-ChildItem -Directory | ? { $_.Name -in @("dependencies","packages") }
    $current = $parent
} until ($childDirectories)
$bacon = $parent.FullName

I should say that the first line $current = Get-Item . 我应该说第一行$current = Get-Item . will only work as is if the current path for the PowerShell runspace is at the end of the tree you are working with. 仅当PowerShell运行空间的当前路径在您正在使用的树的末尾时,它才能按原样工作。

In your script, if you are using v3, you can replace the . 在脚本中,如果您使用的是v3,则可以替换. with $PSScriptRoot . $PSScriptRoot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM