String comparison not working in PowerShell function - what am I doing wrong?

倖福魔咒の 提交于 2019-12-12 10:54:32

问题


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.


回答1:


$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.."
}



回答2:


Just a note that the -notcontains operator 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:

if ( -not $q.Contains("nothing to commit") )

I.e., use the Contains method of the String object, which does return $true if a string contains a substring.



来源:https://stackoverflow.com/questions/16258074/string-comparison-not-working-in-powershell-function-what-am-i-doing-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!