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

[玩转系统] 使用 PowerShell 获取 Git

作者:精品下载站 日期:2024-12-14 07:51:29 浏览:13 分类:玩电脑

使用 PowerShell 获取 Git


如果您现在正在创建 PowerShell 脚本、工具或模块,那么您很可能会使用 Git。什么?你不?是因为你还没来得及安装吗?我有一些“快速而肮脏”的 PowerShell 技巧可以帮助您解决 Windows 系统上的问题。 Linux 男孩和女孩已经知道该做什么了。

当然,您可以运行搜索来查找最新版本 Git 的下载链接。或者,如果您使用 Chocolatey,您很可能知道如何查找和安装软件包。但也许您不(或不能)使用 Chocolatey。没关系。 PowerShell 可以快速完成这项任务。

#download the latest 64bit version of Git for Windows
$uri = 'https://git-scm.com/download/win'
#path to store the downloaded file
$path = $env:temp

#get the web page
$page = Invoke-WebRequest -Uri $uri -UseBasicParsing 

#get the download link
$dl = ($page.links | where outerhtml -match 'git-.*-64-bit.exe' | select -first 1 * ).href

#split out the filename
$filename = split-path $dl -leaf

#construct a filepath for the download
$out = Join-Path -Path $path -ChildPath $filename

#download the file
Invoke-WebRequest -uri $dl -OutFile $out -UseBasicParsing

#check it out
Get-item $out

我的代码假设您在 64 位系统上运行。评论应该解释这一切是如何运作的。运行时,您将获得最新的安装可执行文件。我建议手动安装它,以便您可以根据需要进行配置。

与此相关,您可能需要一个合并冲突工具。我用的是kdiff3。这是类似的下载代码。

$k = invoke-webrequest https://sourceforge.net/projects/kdiff3/files/kdiff3/0.9.98/KDiff3-64bit-Setup_0.9.98-2.exe/download -UseBasicParsing
$dl = $k.links | where href -match downloads
$dluri = $dl.href.split("?")[0]
$filename = Split-Path $dluri -Leaf
$out = Join-Path $path -ChildPath $filename

Invoke-WebRequest -uri $dluri -OutFile $out -UseBasicParsing

get-item $out

再次,继续手动安装。

我的最后一个 git hack 是使用 PowerShell 来获取版本。如果你安装了git,就可以轻松运行

git --version

在 Windows 中,您将获得类似 git 版本 2.14.1.windows.1 的内容。但作为一名 PowerShell 极客,我只想显示版本号。所以我使用正则表达式来提取值。

$v = git --version
[regex]$rx ="(\d+\.){1,}\d+"
$rx.match($v).value

相同的代码也适用于 Linux 上的开源 PowerShell。虽然Windows用户也可以检查注册表:

Get-itemproperty HKLM:\SOFTWARE\GitForWindows | Select CurrentVersion,InstallPath

想要查看适用于 Windows 的最新 git 版本以了解是否需要下载?使用此功能。

Function Get-GitCurrentRelease {
[cmdletbinding()]
Param(
[ValidateNotNullorEmpty()]
[string]$Uri = "https://api.github.com/repos/git-for-windows/git/releases/latest"
)

Begin {
    Write-Verbose "[BEGIN  ] Starting: $($MyInvocation.Mycommand)"  

} #begin

Process {
    Write-Verbose "[PROCESS] Getting current release information from $uri"
    $data = Invoke-Restmethod -uri $uri -Method Get

    
    if ($data.tag_name) {
    [pscustomobject]@{
        Name = $data.name
        Version = $data.tag_name
        Released = $($data.published_at -as [datetime])
      }
   } 
} #process

End {
    Write-Verbose "[END    ] Ending: $($MyInvocation.Mycommand)"
} #end

}

[玩转系统] 使用 PowerShell 获取 Git

有趣吧?现在没有理由在 Windows 桌面上设置 git。

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

取消回复欢迎 发表评论:

关灯