周五乐趣:使用 PowerShell 查找 Git 提示
最近,我发布了一个 PowerShell 函数,用于显示随机的 Git 每日提示。该功能依赖于我在 GitHub 上克隆的 Git-Tips 项目。我一直在密切关注这个项目,并提出了一个关于创建命令行实用程序来搜索提示列表的问题。现在,这个项目很可能是针对开发人员的,至少根据我在问题列表中看到的内容。但对于 PowerShell 用户来说,这是一件非常简单的事情。
我已经有该项目的本地克隆,其中包含一个 json 文件。正如在我的 Show-GitTip 脚本中一样,我知道我可以使用 ConvertFrom-Json 将 json 文件转换为对象。该对象有一个 title 属性,因此使用Where-Object 来过滤单词并不困难。所以我很快组合了一个新函数,我称之为 Find-GitTip。
Find-GitTip.ps1:
#requires -version 4.0
Function Find-GitTip {
<#
.Synopsis
Search Git tips
.Description
This function will search the Tips.json file from the Git-Tips project on GitHub. You will need to clone or download the git-tips project locally from https://github.com/git-tips/tips.
.Parameter Text
The search term which can be a regular expression pattern.
.Parameter Path
The path to the tips.json file from the GitHub project.
.Example
find-gittip status
title tip
----- ---
Status of ignored files. git status --ignored
Find all tips with 'status' in the tip title.
.Example
find-gittip \bignore\b | format-list
title : Ignore one file on commit (e.g. Changelog).
tip : git update-index --assume-unchanged Changelog; git commit -a; git update-index
--no-assume-unchanged Changelog
title : Ignore file mode changes on commits
tip : git config core.fileMode false
Find all tips that contain the word 'ignore' and display as a formatted list.
.Notes
version: 1.0
Learn more about PowerShell:
http://jdhitsolutions.com/blog/essential-powershell-resources/
.Link
ConvertFrom-Json
.Link
https://github.com/git-tips/tips
#>
[cmdletbinding()]
Param(
[Parameter(
Position = 0,
Mandatory,
HelpMessage = "enter a search word or regex pattern."
)]
[ValidateNotNullorEmpty()]
[string]$Text,
[ValidateScript({
if (Test-Path $_) {
$True
}
else {
Throw "Cannot validate path $_"
}
})]
[string]$Path = 'c:\scripts\tips\tips.json'
)
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "Searching for $text from $path"
#convert each to a pscustomobject
Get-Content -Path $path | ConvertFrom-Json |
foreach {$_ -as [pscustomobject]} |
where {$_.title -match $text}
Write-Verbose "Ending: $($MyInvocation.Mycommand)"
}
#define an alias
Set-Alias -Name greptip -Value Find-GitTip
该函数将搜索提示标题中的任何文本:
您还可以使用正则表达式。
我定义该函数的脚本文件还定义了一个别名,您当然可以更改该别名。
我希望你能让我知道你的想法。如果您遇到任何问题,请将其发布到该脚本的要点页面上。
享受!