0

I'm trying to loop through multiple files to see if a job completed. I'm very new to powershell and am trying to understand the basics of how looping works before creating a more detailed program. I can't figure out what's wrong in my code. When I run the program no output ("Success" or "Fail") is displayed. Any suggestions on looping through sql directory files to search for a specific string appreciated too:)

Get-ChildItem "C:\Users\afila\Desktop\TEST" -Filter "*.txt" |
ForEach-Object{
if(Object.Contains("*Loaded successfully*"))
{
    Write-Host "Success" 
}
else
{
    Write-Host "Fail"
}

}

2 Answers 2

1

Use $_ where you have Object.Contains. It should read "$_.Contains".

Since you are using wildcards in your IF statement, you may also try -like. -like, by default, treats the search with wildcards:

Get-ChildItem "C:\Users\afila\Desktop\TEST" -Filter "*.txt" |
ForEach-Object{
if($_ -like "Loaded successfully")
{
    Write-Host "Success" 
}
else
{
    Write-Host "Fail"
}
Sign up to request clarification or add additional context in comments.

2 Comments

The entire purpose of -like is wildcard operations, so there is no other behavior.
That's what I said? "-Like treats the search with wildcards".
0

When using the pipeline you have to use $_ to represent the object passed down the pipeline. For example

Get-ChildItem C:\temp\ -Filter "txt" | 

Foreach-Object{
    if($_.Contains("my test info"))
    {
       write-host "success"
    }
}

The $_ is similar to the word "this" in other languages and is just a representation of the current object.

1 Comment

It's nothing like this because that construct already exists within PowerShell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.