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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With