String comparison not working in PowerShell function - what am I doing wrong?
git, powershell, scripting, shell, windows
Solution
`$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.."
}
Problem
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.