Powershell -match in function - 返回时获得额外的true / false

时间:2014-11-28 18:22:06

标签: regex powershell hashtable

为什么我得到提取物" True"或"错误" (当我想回来的只是邮政编码时)这个函数的结果:

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" 

运行时间的结果:

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

$returnZipcode=12345
Zip='False 12345' from keyword=Somewhere in Dallas Texas 

1 个答案:

答案 0 :(得分:4)

如果模式匹配,则行$keyword -match $pattern会返回$True,否则会返回$False。由于您没有对该值执行任何其他操作,因此从函数输出。

尝试:

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

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

无论你是用Write-Output明确地写它还是用return返回它,或者只是隐含地输出一个输出结果的管道,函数输出的任何值都会成为结果的一部分。

如果您不希望从函数输出管道输出,请将其分配给变量。 e.g。

$m = $keyword -match $pattern

或重定向:

$keyword -match $pattern >$null

或:

$keyword -match $pattern | Out-Null

或将其发送到另一个输出流:

Write-Verbose ($keyword -match $pattern)

通过设置$VerbosePreference='Continue'(或将您的函数设置为cmdlet并在调用时使用-Verbose标志)使您可以看到它的范围。虽然在最后一种情况下我仍会首先将它分配给变量:

$m = $keyword -match $pattern
Write-Verbose "GetZipCodeFromKeyword RegEx match: $m"