【问题标题】:Powershell -match in function - gets extra true/false when returnedPowershell -match in function - 返回时获得额外的真/假
【发布时间】:2014-11-28 18:22:06
【问题描述】:

为什么我会在此函数的结果中得到提取“True”或“False”(当我想要返回的只是邮政编码时):

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 

【问题讨论】:

标签: regex powershell hashtable


【解决方案1】:

如果模式匹配,$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 返回它,或者只是隐式地拥有一个输出结果的管道,函数的任何输出值都会成为结果的一部分。

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

$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" 

【讨论】:

  • 所以我得到了一个数组,即使我专门只返回了 $returnZipCode?我该如何摆脱它?
  • 好吧,这似乎有效:“$isMatch = $keyword -match $pattern” - 我想这可以防止返回真/假,可以说是“吞下它”。跨度>
猜你喜欢
  • 1970-01-01
  • 2020-11-16
  • 2023-03-03
  • 1970-01-01
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-17
相关资源
最近更新 更多