How to evaluate whether a string is present in an array in Powershell?

Asked

Viewed 138 times

3

I’m writing a git hook to check if the commit message matches an array of words.

$array = @('Adiciona', 'Altera', 'Corrige', 'Refatora', 'Remove')
$msg = "Coloca coisas ao projeto."

if (!($msg.toLower().Contains($array.toLower()))){
    Write-Host ""
    Write-Host -ForegroundColor "DarkGreen" "Mensagem de confirmação segue o formato."
    Write-Host "`r`nConfirmando alterações ao git.`r`n"

    return 0
}
elseif ($msg.toLower().Contains($array.toLower())){
    Write-Host ""
    Write-Host -ForegroundColor "DarkRed" "Mensagem de confirmação não segue o formato!"
    Write-Host "`r`nA mensagem de confirmação precisa começar com as seguintes palavras:`r`n"
    $array | Sort
    Write-Host "`r`nAlterações não foram confirmadas ao git.`r`n"

    return 1
}

At the value in $msg, is expected to return the script False and display the content of elseif, but it returns the content of if as if $msg were True. What I’m doing wrong?

  • I’m sorry if I wasn’t clear, I’ve been trying to figure this out since dawn and neither vision nor cognition is working out.

  • It seems that you are checking whether a string contains an array... it would not be better to go through that array and check that each element of it is in the string?

  • 1

    @Gabrielhardoim, thanks for the comment. I did it with ForEach and the result was a return of False five times, one for each element in the array.

  • Show! test with another string to see if it returns true as well!

1 answer

1

Your script is small and simple, simply opening the Windows Powershell ISE and executing step by step would already have understood.

To debug your script do as follows:

  1. Save your script locally.
  2. Add a breakpoint with the key F9.
  3. Then run the script with the key F5.
  4. Press F11 to run the program line by line.

You may need to change your script execution policy, so run the script below:

Set-ExecutionPolicy Bypass -Scope CurrentUser

Besides, the problem is in the logic of your if. Notice that with the operator ! you are denying the outcome of your condition.

So the condition below returns false:

$msg.toLower().Contains($array.toLower())

But the use of ! in front, reverses the logic, thus making the script enter your if. Just remove it and you’re done.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.