Powershell, using contains to check if files contain a certain word

Simplified contains clause

$file = Get-Content $_.FullName

if ((Get-Content $file | %{$_ -match $wordToFind}) -contains $true) {
    Add-Content log.txt $_.FullName
    ($file) | ForEach-Object { $_ -replace $wordToFind , $wordToReplace } | 
    Set-Content $_.FullName
}

Try this:

$directoryToTarget=$args[0]
$wordToFind=$args[1]
$wordToReplace=$args[2]

Clear-Content log.txt

Get-ChildItem -Path $directoryToTarget -Filter *.properties -Recurse | where { !$_.PSIsContainer } | % { 

$file = Get-Content $_.FullName
$containsWord = $file | %{$_ -match $wordToFind}
If($containsWord -contains $true)
{
    Add-Content log.txt $_.FullName
    ($file) | ForEach-Object { $_ -replace $wordToFind , $wordToReplace } | 
     Set-Content $_.FullName
}

}

This will put the content of the file into an array $file then check each line for the word. Each lines result ($true/$false) is put into an array $containsWord. The array is then check to see if the word was found ($True variable present); if so then the if loop is run.

Tags:

Powershell