2

This method should take in a string, and return true if it is all zeros or false if there is at least one other character in the string:

Function check0ID($fixedString) {

    foreach ($char in $fixedString) {
        If ($char -ne "0") {
            $false
        }
    }

    $true

}

This method will return:

false true

even when the string is not all zeros. Why doesn't this method stop after returning $false? NB If you want to give a more efficient method with the same functionality, please do :)

user3772119
  • 484
  • 3
  • 7
  • 16

2 Answers2

4

There are two things here:

  1. You need to explicitly use the return keyword to exit a function prematurely. For more information, see Function return value in PowerShell.

  2. You need to call the System.String.ToCharArray method on $fixedString so that it is treated as an array of characters. Otherwise, $char will be equal to $fixedString within the loop body. You can see this for yourself by adding the following line just under the loop header:

    Write-Host "`$char equals $char"
    

Below is a fixed version of your script:

Function check0ID($fixedString) {

    foreach ($char in $fixedString.ToCharArray()) {
        If ($char -ne "0") {
            return $false
        }
    }

    $true

}
Community
  • 1
  • 1
2

You're making this way too complicated. Instead of doing all the micro-management of iterating over all characters in a string, you could simply do a regexp match and return the result:

function ContainsNonZero($fixedString) {
  [bool]($fixedString -match '[^0]')
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • This is faster than the method described in the other answer but I accepted @iCodez because he explained why what I was doing wasn't working...I still up voted your answer, though! Thanks! – user3772119 Jun 27 '14 at 16:07