user664481
user664481

Reputation: 2301

PowerShell - Return True if string matches a condition

How do I return a True value from PowerShell if a string matches conditions?

Example: If the first line of the text file is Success then PowerShell will return True condition else False.

Here the code I wrote:

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

Here the message returns from PowerShell. What is wrong here?

Get-Content : A parameter cannot be found that matches parameter name 'first'.

Upvotes: 2

Views: 52449

Answers (3)

Matt
Matt

Reputation: 46680

Your problem is covered in the comments and came to light when you updated your question. Get-Content did not support the -TotalCount parameter until 3.0. -First is an alias for -TotalCount. Running 2.0 I can simulate your issue.

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

Hopefully the file is not too big. If not then you can just pipe into Select-Object or just use array indexing.

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

The drawback in both cases is the whole file will be read into memory to just to drop the rest of it.

Upvotes: 2

Chris Barber
Chris Barber

Reputation: 513

Depending on what sort of conditions you want to check, you can use any of the PowerShell comparison operators to get a true/false result (see about_Comparison_Operators for details).

For example, you could check if a string matches exactly using the -eq operator:

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

Note: PowerShell comparison operators are case insensitive. If you want your comparison to be case sensitive you should prepend the operator with "c", for example, -eq becomes -ceq.

Upvotes: 1

Martin
Martin

Reputation: 1963

Just return the result of the comparison:

$a = ($something -eq $something_else), etc.

In a function use the return statement.

In your example:

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

Maybe in simpler words: The result of a comparison, match, etc. is already a true/false value. So with your string match condition:

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

Upvotes: 3

Related Questions