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"
}
}
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.
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"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.