[英]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.