如何以递归方式查找PowerShell中包含.hg文件夹的所有文件夹

时间:2012-02-01 07:16:09

标签: powershell mercurial

我正在尝试在PowerShell中编写一个脚本来备份我们的Mercurial存储库集合。

我从这开始:

$repos=Get-ChildItem C:\hgrepos|Where-Object { $_.PSIsContainer }

这将获得C:\ hgrepos下的第一级文件夹,这通常没问题,因为这是我们的存储库所在的位置。但是,存在子库。所以我需要递归。最重要的是,只列出包含.hg子文件夹的文件夹

3 个答案:

答案 0 :(得分:7)

您可以使用-recurse

中的Get-ChildItem标记

会是这样的:

gci c:\hgrepos -recurse -include ".hg" | %{$_.Parent}

答案 1 :(得分:1)

我编写了这个PowerShell函数来备份我们的Mercurial存储库:

function BackupHg
{
    param($repositoryRoot, $destination)

    # The path to the Hg executable
    $hg = """C:\Python26\hg.bat"""

    # Get the list of repos
    Get-ChildItem $repositoryRoot | 
        Where { $_.psIsContainer -eq $true } |
        ForEach -Process { 
            $repo = $_.FullName 
            $folder = $_.Name

            if (Test-Path "$repo\.hg") {
                $cmdLine = "$hg clone -U $repo $destination\$folder"
                cmd /c $cmdLine
            }
            else {
                New-Item "$destination\$folder" -type directory
                BackupHg "$repositoryRoot\$folder" "$destination\$folder"
            }
        }    
}

您传入根文件夹和备份目标,它会查找所有文件夹,测试它是否为Mercurial存储库(查找.hg目录)并将存储库克隆到备份目标。如果文件夹不是Mercurial repo,那么它会自己进行递归。

这样做是因为我们使用文件夹来组织我们的存储库,因此每个客户端的所有代码都在与其他客户端分开的自己的文件夹中。

最后一点。 Mercurial子存储库的存在并不意味着您需要递归。除非您有一个包含工作副本的存储库,否则您的子存储库不会存储在存储库中,应该由存储在其中的任何系统进行备份。如果这是与存储库相同的系统,那么它将是您的存储库文件夹中的另一个存储库,并将通过上述脚本进行备份。

例如,我们有一个WebApp存储库,其中包含一个客户端的WebControls子存储库,文件结构如下:

C:\Repositories\Hg\Client\WebApp
C:\Repositories\Hg\Client\WebControls

WebControls未存储在WebApp文件夹中,即使它是它的子存储库。

答案 2 :(得分:0)

我最终使用下面的脚本。感谢Steve Kaye和manojlds提供了非常需要的反馈!

function BackupHg
{
    param($repositoryRoot, $destination)

    Remove-Item "$destination\*" -recurse

    # The path to the Hg executable
    $hg = """C:\Python27\Scripts\hg.bat"""

    # Get the list of repos
    Get-ChildItem $repositoryRoot -recurse | 
        Where { $_.psIsContainer -eq $true } |
        ForEach -Process { 
            $repo = $_.FullName 
            $folder = $_.FullName.Replace($repositoryRoot, $destination)


            if (Test-Path "$repo\.hg") {
                if (!(Test-Path "$folder")) {
                    New-Item "$folder" -type directory
                }
                $cmdLine = "$hg clone -U $repo $folder"
                write-host $cmdLine
                cmd /c $cmdLine
            }
        }    
}
相关问题