PowerShell/scripts/list-branches.ps1

51 lines
1.5 KiB
PowerShell
Raw Normal View History

2024-10-01 15:11:03 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2023-04-12 14:13:56 +02:00
Lists Git branches
2021-07-13 21:10:02 +02:00
.DESCRIPTION
2024-03-18 11:32:35 +01:00
This PowerShell script lists branches in a Git repository - either all (default) or by a search pattern.
.PARAMETER pathToRepo
2021-10-15 23:09:08 +02:00
Specifies the path to the Git repository (current working directory by default)
2024-03-18 11:32:35 +01:00
.PARAMETER searchPattern
Specifies the search pattern ("*", anything by default)
2021-07-13 21:10:02 +02:00
.EXAMPLE
2023-08-06 21:35:36 +02:00
PS> ./list-branches.ps1
List of Git Branches
--------------------
main
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-29 12:47:46 +01:00
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2021-02-28 18:26:20 +01:00
#>
2024-03-18 11:32:35 +01:00
param([string]$pathToRepo = "$PWD", [string]$searchPattern = "*")
2021-02-28 18:26:20 +01:00
try {
2024-03-18 11:32:35 +01:00
if (-not(Test-Path "$pathToRepo" -pathType container)) { throw "Can't access repo folder '$pathToRepo' - maybe a typo or missing folder permissions?" }
2021-02-28 19:05:36 +01:00
2024-03-18 11:32:35 +01:00
$null = (git --version)
2021-03-10 10:51:59 +01:00
if ($lastExitCode -ne "0") { throw "Can't execute 'git' - make sure Git is installed and available" }
2024-03-18 11:32:35 +01:00
& git -C "$pathToRepo" fetch
2021-05-10 16:31:13 +02:00
if ($lastExitCode -ne "0") { throw "'git fetch' failed" }
2021-03-10 10:51:59 +01:00
2024-03-18 11:32:35 +01:00
$branches = $(git -C "$pathToRepo" branch --list --remotes --no-color --no-column)
2021-02-28 19:05:36 +01:00
if ($lastExitCode -ne "0") { throw "'git branch --list' failed" }
2021-02-28 18:26:20 +01:00
2021-05-10 16:31:13 +02:00
""
"List of Git Branches"
"--------------------"
2024-03-18 11:32:35 +01:00
foreach($branch in $branches) {
if ("$branch" -match "origin/HEAD") { continue }
$branchName = $branch.substring(9)
if ("$branchName" -notlike "$searchPattern") { continue }
"$branchName"
2021-03-01 12:05:26 +01:00
}
2021-05-10 16:31:13 +02:00
""
2021-09-27 10:09:45 +02:00
exit 0 # success
2021-02-28 18:26:20 +01:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-02-28 18:26:20 +01:00
exit 1
}