当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 查找 Git 存储库

作者:精品下载站 日期:2024-12-14 07:48:57 浏览:15 分类:玩电脑

使用 PowerShell 查找 Git 存储库


作为今年持续改进过程的一部分,我开始更多地使用 Git。昨天,我发布了一篇文章,其中包含我的 PowerShell 脚本,用于创建一个新的项目文件夹,其中包括创建一个 Git 存储库。我面临的挑战是,我并不总是记得我用 Git 设置了什么以及没有设置什么。因此,我组合了一个小小的 PowerShell 函数来识别包含 Git 存储库的文件夹。

Find-GitRepository 函数采用顶级路径作为参数。然后该函数搜索所有子文件夹,搜索名为 .git 的隐藏目录。对于每个目录,该函数都会创建一个自定义对象,其中包含有关 Git 存储库的路径和详细信息。为了获取这些值,命令跳转到我解析 gitbranch 和 git log 结果的每个文件夹。

[玩转系统] 使用 PowerShell 查找 Git 存储库

我可能可以使用 Git 获取更多信息,但现在这对我来说似乎已经足够了。您可以在我的 Github 存储库中找到该函数的要点。

Find-GitRepository.ps1:


Function Find-GitRepository {

 Find-GitRepository -path D:\Projects

Repository             Branch LastAuthor     LastLog             
----------             ------ ----------     -------             
D:\Projects\Excalibur  master jdhitsolutions 4/17/2016 9:59:02 AM
D:\Projects\PiedPiper  bug    jdhitsolutions 5/16/2016 1:15:03 PM
D:\Projects\PSMagic    master jdhitsolutions 5/11/2016 1:27:35 PM
D:\Projects\ProjectX   dev    jdhitsolutions 4/12/2016 4:49:30 PM

.NOTES
NAME        :  Find-GitRepository
VERSION     :  1.0.0   
LAST UPDATED:  5/17/2016
AUTHOR      :  Jeff Hicks (@JeffHicks)

Learn more about PowerShell:
http://jdhitsolutions.com/blog/essential-powershell-resources/

  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************
.LINK
https://gist.github.com/jdhitsolutions/ba3295167ccc997b7714e1f2a2777405
.INPUTS
[string]
.OUTPUTS
[pscustomobject]
#>

[cmdletbinding()]
Param(
[Parameter(
Position = 0,
HelpMessage = "The top level path to search"
)]
[ValidateScript({
if (Test-Path $_) {
   $True
}
else {
   Throw "Cannot validate path $_"
}
})]    
[string]$Path = "."
)

Write-Verbose "[BEGIN  ] Starting: $($MyInvocation.Mycommand)"
Write-Verbose "[PROCESS] Searching $(Convert-Path -path $path) for Git repositories"

dir -path $Path -Hidden -filter .git -Recurse | 
select @{Name="Repository";Expression={Convert-Path $_.PSParentPath}},
@{Name ="Branch";Expression = {
 #save current location
 Push-Location
 #change location to the repository
 Set-Location -Path (Convert-Path -path ($_.psparentPath))
 #get current branch with out the leading asterisk
 (git branch).where({$_ -match "\*"}).Substring(2)
 
}},
@{Name="LastAuthor";Expression = { git log --date=local --format=%an -1 }},
 @{Name="LastLog";Expression = {
  (git log --date=iso --format=%ad -1 ) -as [datetime]
 #change back to original location
 Pop-Location
 }}

Write-Verbose "[END    ] Ending: $($MyInvocation.Mycommand)"

} #end function

与我之前的脚本一样,我假设您的路径中有 git 命令行工具。如果你使用 Git,我希望你能尝试一下并让我知道你的想法。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯