PowerShell - 如果字符串匹配条件,则返回True

时间:2016-03-04 13:02:42

标签: powershell

如果字符串符合条件,如何从PowerShell返回True值?

示例:如果文本文件的第一行是Success,那么PowerShell将返回True条件,否则返回False。

这里是我写的代码:

IF ((get-content -path $outPath3 -first 1) -like 'Successfully generated*'){$Time=Get-Date}
Else {Send-MailMessage xxxxxxxx}

此处消息从PowerShell返回。这有什么不对?

  

Get-Content:找不到与参数名称匹配的参数' first'。

3 个答案:

答案 0 :(得分:1)

根据您要检查的条件类型,您可以使用任何PowerShell比较运算符来获取真/假结果(有关详细信息,请参阅about_Comparison_Operators)。

例如,您可以使用if ($InputString -eq $StringToMatch) { // TRUE } else { // FALSE } 运算符检查字符串是否完全匹配:

-eq

注意:PowerShell比较运算符不区分大小写。如果您希望比较区分大小写,则应在操作符前加上" c",例如,-ceq变为deploy-1: do_stuff $(host1) deploy-2: do_stuff $(host2) deploy: deploy-1 deploy-2 deploy-production: deploy-1 deploy-2

答案 1 :(得分:1)

您的问题已在评论中涵盖,并在您更新问题时曝光。直到3.0,Get-Content才支持"Start Date: 2015-1-1 End Date: 2017-1-1 Warranty Type: XXX Status: Active Serial Number/IMEI: XXXXXXXX Description: This product has a three year limited warranty and is entitled to parts, labor and on-site repair service. Service is available Monday-Friday, except holidays, with a next business day response objective. Many parts can also be delivered to you using the Customer Replaceable Unit (CRU) method." 参数。 -TotalCount-First的别名。运行2.0我可以模拟你的问题。

-TotalCount

希望文件不要太大。如果没有,那么您可以直接进入PS C:\Users> Get-Host | Select version Version ------- 2.0 PS C:\Users> Get-Content C:\temp\anothertext.txt -first Get-Content : A parameter cannot be found that matches parameter name 'first'. At line:1 char:43 + Get-Content C:\temp\anothertext.txt -first <<<< + CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand 或只使用数组索引。

Select-Object

这两种情况的缺点是整个文件将被读入内存,只是为了删除剩下的内容。

答案 2 :(得分:0)

只需返回比较结果:

$a = ($something -eq $something_else)

在函数中使用return语句。

在你的例子中:

$a = ((get-content -path '.\file.txt' -first 1)-eq "Success")

也许用简单的话说:比较,匹配等的结果已经是真/假值。所以你的字符串匹配条件:

if ($string -match "something")  # The term in brackets is a true/false value
{
    # Statement is True
}
else {
    # Statement is False
}