PowerShell/Docs/list-repos.md
2023-07-29 10:34:04 +02:00

3.0 KiB

list-repos.ps1

This PowerShell script lists the details of all Git repositories in a folder.

Parameters

PS> ./list-repos.ps1 [[-ParentDir] <String>] [<CommonParameters>]

-ParentDir <String>
    Specifies the path to the parent directory.
    
    Required?                    false
    Position?                    1
    Default value                "$PWD"
    Accept pipeline input?       false
    Accept wildcard characters?  false

[<CommonParameters>]
    This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, 
    WarningVariable, OutBuffer, PipelineVariable, and OutVariable.

Example

PS> ./list-repos C:\MyRepos



No   Repository    Branch    LatestTag    Status
--   ----------    ------    ---------    ------
1    cmake         main      v3.23.0      clean
2    opencv        main      4.5.5        modified
...

Notes

Author: Markus Fleschutz | License: CC0

https://github.com/fleschutz/PowerShell

Script Content

<#
.SYNOPSIS
	Lists Git repositories
.DESCRIPTION
	This PowerShell script lists the details of all Git repositories in a folder.
.PARAMETER ParentDir
	Specifies the path to the parent directory.
.EXAMPLE
	PS> ./list-repos C:\MyRepos
	
	No   Repository    Branch    LatestTag    Status
	--   ----------    ------    ---------    ------
	1    cmake         main      v3.23.0      clean
	2    opencv        main      4.5.5        modified
	...
.LINK
	https://github.com/fleschutz/PowerShell
.NOTES
	Author: Markus Fleschutz | License: CC0
#>

param([string]$ParentDir = "$PWD")

function ListRepos { 
	[int]$No = 1
	$Folders = (Get-ChildItem "$ParentDir" -attributes Directory)
	foreach($Folder in $Folders) {
		$FolderName = (Get-Item "$Folder").Name
		$Branch = (git -C "$Folder" branch --show-current)
		$LatestTagCommitID = (git -C "$Folder" rev-list --tags --max-count=1)
	        $LatestTag = (git -C "$Folder" describe --tags $LatestTagCommitID)
		$Status = (git -C "$Folder" status --short)
		if ("$Status" -eq "") { $Status = "clean" }
		elseif ("$Status" -like " M *") { $Status = "MODIFIED" }
		$NumCommits = (git -C "$Folder" rev-list HEAD...origin/$Branch --count)
		New-Object PSObject -property @{ 'No'="$No"; 'Repository'="$FolderName"; 'Branch'="$Branch"; 'Latest_Tag'="$LatestTag"; 'Status'="$Status$NumCommits"; }
		$No++
	}
}

try {
	if (-not(Test-Path "$ParentDir" -pathType container)) { throw "Can't access directory: $ParentDir" }

	$Null = (git --version)
	if ($lastExitCode -ne "0") { throw "Can't execute 'git' - make sure Git is installed and available" }

	ListRepos | Format-Table -property @{e='No';width=3},@{e='Repository';width=22},@{e='Branch';width=20},Latest_Tag,Status
	exit 0 # success
} catch {
	"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
	exit 1
}

(generated by convert-ps2md.ps1 using the comment-based help of list-repos.ps1 as of 07/29/2023 10:33:46)