windows 字符串比较在 PowerShell 函数中不起作用 - 我做错了什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16258074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String comparison not working in PowerShell function - what am I doing wrong?
提问by adrienne
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.
我正在尝试创建一个别名,git commit
它也将消息记录到一个单独的文本文件中。但是,如果git commit
返回"nothing to commit (working directory clean)"
,则不应将任何内容记录到单独的文件中。
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
.
这是我的代码。该git commit
别名作品; 输出到文件有效。但是,无论从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.
我正在使用 PowerShell 3。
回答by Andy Arismendi
$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
包含 Git 标准输出的每一行的字符串数组。要使用,-notcontains
您需要匹配数组中项目的完整字符串,例如:
$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.)
如果要测试部分字符串匹配,请尝试使用-match
运算符。(注意 - 它使用正则表达式并返回匹配的字符串。)
$q -match "nothing to commit"
-match
will work if the left operand is an array. So you could use this logic:
-match
如果左操作数是一个数组,它将起作用。所以你可以使用这个逻辑:
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:
另一种选择是使用-like
/-notlike
运算符。这些接受通配符并且不使用正则表达式。匹配(或不匹配)的数组项将被返回。所以你也可以使用这个逻辑:
if (-not ($q -like "nothing to commit*")) {
"there was something to commit.."
}
回答by Bill_Stewart
Just a note that the -notcontainsoperator doesn't mean "string doesn't contain a substring." It means "collection/array doesn't contain an item." If the "git commit" command returns a single string, you might try something like this:
请注意-notcontains运算符并不意味着“字符串不包含子字符串”。这意味着“集合/数组不包含项目”。如果“git commit”命令返回单个字符串,您可以尝试以下操作:
if ( -not $q.Contains("nothing to commit") )
I.e., use the Containsmethod of the String object, which does return $true if a string contains a substring.
即,使用String 对象的Contains方法,如果字符串包含子字符串,它会返回 $true。