3

Why do I get the extract "True" or "False" (when all I want to get back is just the zip code) on the result of this function:

Function GetZipCodeFromKeyword([String] $keyword)
{
   $pattern = "\d{5}"
   $keyword -match $pattern 
   $returnZipcode = "ERROR" 
   #Write-Host "GetZipCodeFromKeyword RegEx `$Matches.Count=$($Matches.Count)" 
   if ($Matches.Count -gt 0) 
      {
         $returnZipcode = $Matches[0] 
      }

   Write-Host "`$returnZipcode=$returnZipcode"
   return $returnZipcode 
}

cls
$testKeyword = "Somewhere in 77562 Texas "
$zipcode = GetZipCodeFromKeyword $testKeyword 
Write-Host "Zip='$zipcode' from keyword=$testKeyword" 

Write-Host " "
$testKeyword = "Somewhere in Dallas Texas "
$zipcode = GetZipCodeFromKeyword $testKeyword 
Write-Host "Zip='$zipcode' from keyword=$testKeyword" 

Results of run time:

$returnZipcode=77562
Zip='True 77562' from keyword=Somewhere in 77562 Texas 

$returnZipcode=12345
Zip='False 12345' from keyword=Somewhere in Dallas Texas 
NealWalters
  • 17,197
  • 42
  • 141
  • 251
  • because $keyword -match $pattern = True – Paul Nov 28 '14 at 18:25
  • 2
    `return` doesn't mean what you think it means in powershell. See http://stackoverflow.com/questions/10286164/powershell-function-return-value – Eris Nov 28 '14 at 18:28

1 Answers1

10

The line $keyword -match $pattern returns $True if the pattern matches, $False otherwise. Since you don't do anything else with the value it is output from the function.

Try:

Function GetZipCodeFromKeyword([String] $keyword)
{
   $pattern = "\d{5}"
   $returnZipcode = "ERROR" 
   if ($keyword -match $pattern)
      {
         $returnZipcode = $Matches[0] 
      }

   Write-Host "`$returnZipcode=$returnZipcode"
   return $returnZipcode 
}

Any value output from the function becomes part of the result whether you explictly write it with Write-Output or return it with return, or just implicitly have a pipeline that outputs a result.

If you don't want a pipeline output to output from the function assign it to a variable. e.g.

$m = $keyword -match $pattern

or redirect it:

$keyword -match $pattern >$null

or:

$keyword -match $pattern | Out-Null

or send it to another output stream:

Write-Verbose ($keyword -match $pattern)

which leaves you scope to make it visible by setting $VerbosePreference='Continue' (or make your function into a cmdlet and use the -Verbose flag when calling it). Though in this last case I would still assign it to a variable first:

$m = $keyword -match $pattern
Write-Verbose "GetZipCodeFromKeyword RegEx match: $m" 
Duncan
  • 92,073
  • 11
  • 122
  • 156
  • So I'm getting an array back, even though I specifically did a return on just $returnZipCode? How do I get rid of it? – NealWalters Nov 28 '14 at 18:25
  • Okay, this seems to work: "$isMatch = $keyword -match $pattern" - I guess that keeps the true/false from being returned, and "swallows it" so to speak. – NealWalters Nov 28 '14 at 18:27