繁体   English   中英

Powershell-功能匹配-返回时获得额外的true / false

[英]Powershell -match in function - gets extra true/false when returned

为什么我要从此函数的结果中提取“ 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 

如果模式匹配,则$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" 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM