Reputation: 23
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"
}
}
Upvotes: 0
Views: 1086
Reputation: 399
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"
}
Upvotes: 1
Reputation: 1465
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.
Upvotes: 0