2016-03-04 100 views
0

如果字符串匹配条件如何从powershell返回True值?如果文本文件的第一行是Success,那么powershell将返回True条件,否则为False。Powershell - 如果字符串匹配条件返回True

下面的代码,我写

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

这里从PowerShell中的消息返回。这里有什么问题? Get-Content:找不到与参数名称'first'匹配的参数。

+0

你在这里问什么。有关布尔值的一般问题或者您在Get-Content中的具体问题 – Matt

回答

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 } 
+1

在PowerShell中,您实际上不需要使用return语句从函数返回结果。结果总是无论什么被放入管道。 return语句只在需要尽早脱离函数时才需要。 –

+0

@ChrisBarber我想传递TRUE/FALSE到IF语句 – user664481

1

取决于什么样的,你要检查的条件下,你可以使用任何PowerShell的比较操作符来获得一个真/假结果(见about_Comparison_Operators了解详细信息)。

例如,你可以检查一个字符串完全使用-eq运算符匹配:

if ($InputString -eq $StringToMatch) { 
    //TRUE 
} 
else { 
    //FALSE 
} 

注:PowerShell的比较操作不区分大小写,如果你想你的比较是大小写敏感的,你应该在前面加上运营商与“C”,例如-eq变成-ceq。

+0

刚刚更新了我的代码.. – user664481

+1

'-First'标志只在PowerShell 3.0中添加。你的错误表明你在Powershell 2.0。为了解决这个问题,你可以使用'(Get-Content -Path $ outPath3)[0]'来获得第一行。请注意,此方法实际上加载了整个文件。 –

1

您的问题已在评论中进行了报道,并在您更新问题时发现。在3.0之前,Get-Content不支持-TotalCount参数。 - 首先是-TotalCount的别名。 Runnning 2.0我可以模拟你的问题。

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或者只是使用数组索引。

if((get-content -path $outPath3)[0] -like 'Successfully generated*') 
if((get-content -path $outPath3 | Select -First 1) -like 'Successfully generated*') 

这两种情况的缺点是整个文件将被读入内存中,只是放下其余部分。

+0

为什么不使用'Select-String'在所需字符的匹配上返回true? – user4317867

+0

@ user4317867主要是因为条件在第一行。不知道该文本是否会出现在其他地方,并且这可能更简单。也解释了他为什么做不起作用。 – Matt

+0

我使用了if((get-content -path $ outPath3)[0] -like'Successfully generated *'),但结果不正确。然后,我写了脚本:IF((get-content -path $ outPath3)| Select -Index 0 | Where-Object {$ _ -like'Successfully generated *'}),它起作用。谢谢 – user664481

相关问题