String comparison doesn't work in PowerShell function - what am I doing wrong?

I am trying to make a git commit alias that also writes the message to a separate text file. However, if git commit returns "nothing to commit (working directory clean)" , it should NOT write anything to a separate file.

Here is my code. Alias git commit works; output to a file works. However, it logs the message no matter what is returned from 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 am using PowerShell 3.

+6
source share
2 answers

$q contains a string array of each Git stdout line. To use -notcontains , you will need to combine the full string of the element in the array, for example:

 $q -notcontains "nothing to commit, working directory clean" 

If you want to check for partial line matches, try the -match . (Note: It uses regular expressions and returns a string that matches.)

 $q -match "nothing to commit" 

-match will work if the left operand is an array. So you can use this logic:

 if (-not ($q -match "nothing to commit")) { "there was something to commit.." } 

Another option is to use the -like / -notlike . They accept wildcards and do not use regular expressions. An array element that matches (or doesn't match) will be returned. So you can also use this logic:

 if (-not ($q -like "nothing to commit*")) { "there was something to commit.." } 
+8
source

Just note that the -notcontains statement does not mean that the string does not contain a substring. “This means that the“ collection / array does not contain an element. ”If the“ git commit ”command returns a single line, you can try something like this:

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

ie, use the Contains method of a String object that returns $ true if the string contains a substring.

Bill

+3
source

Source: https://habr.com/ru/post/943793/


All Articles