字符串比较在PowerShell函数中不起作用 - 我做错了什么? [英] String comparison not working in PowerShell function - what am I doing wrong?
问题描述
我正在尝试制作 git commit
的别名,该别名也会将邮件记录到单独的文本文件中。但是,如果 git commit
返回没有提交(工作目录干净)
,它不应该记录任何东西到单独的文件。
这是我的代码。 git commit
别名有效;输出到文件的作品。但是,无论从 git commit
中返回的内容如何,它都会记录消息。
git-commit-and-log($ msg)
{
$ q = git commit -a -m $ msg
$ q
if($ q - notcontainsnothing to commit){
$ msg | Out-File w:\ log.txt -Append
}
}
Set-Alias -Name gcomm -Value git-commit-and-log
我使用的是PowerShell 3.
$ q
包含每行Git stdout的字符串数组。要使用 -notcontains
,您需要匹配数组中一个项目的完整字符串,例如:
<$
$ q -notcontains没有提交,工作目录干净 p>如果要测试部分字符串匹配,请尝试
-match
运算符。 (注意 - 它使用正则表达式并返回匹配的字符串。)
$ q -matchnothing to commit
-match
如果左操作数是数组。所以你可以使用这个逻辑:
if(-not($ q -matchnothing to commit)){
有东西要提交..
}
另一个选择是使用 -like
/ -notlike
运算符。这些接受通配符并且不使用正则表达式。匹配(或不匹配)的数组项将被返回。所以你也可以使用这个逻辑:
if(-not($ q -likenothing to commit *)){
有东西要提交..
}
I'm trying to make an alias of git commit
which also logs the message into a separate text file. However, if git commit
returns "nothing to commit (working directory clean)"
, it should NOT log anything to the separate file.
Here's my code. The git commit
alias works; the output to file works. However, it logs the message no matter what gets returned out of git commit
.
function git-commit-and-log($msg)
{
$q = git commit -a -m $msg
$q
if ($q –notcontains "nothing to commit") {
$msg | Out-File w:\log.txt -Append
}
}
Set-Alias -Name gcomm -Value git-commit-and-log
I'm using PowerShell 3.
$q
contains a string array of each line of Git's stdout. To use -notcontains
you'll need to match the full string of a item in the array, for example:
$q -notcontains "nothing to commit, working directory clean"
If you want to test for a partial string match try the -match
operator. (Note - it uses regular expressions and returns a the string that matched.)
$q -match "nothing to commit"
-match
will work if the left operand is an array. So you could use this logic:
if (-not ($q -match "nothing to commit")) {
"there was something to commit.."
}
Yet another option is to use the -like
/-notlike
operators. These accept wildcards and do not use regular expressions. The array item that matches (or doesn't match) will be returned. So you could also use this logic:
if (-not ($q -like "nothing to commit*")) {
"there was something to commit.."
}
这篇关于字符串比较在PowerShell函数中不起作用 - 我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!