Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

I am trying to create a powershell script which looks through all files and folders under a given directory it then changes all instances of a given word in .properties files to an instance of another given word.

What I have written below does this however my version control notices a change in every single file regardless of whether it contains an instance of the word to change. To counter this I tried to put in a check to see whether the word is present or not in the file before I get/set the content (shown below) however it tells me that [System.Object[]] doesn't contain a method named 'Contains'. I assumed this meant that $_ was an array so I tried to create a loop to go through it and check each file at a time however it told me it was Unable to index into an object of type System.IO.FileInfo.

Could anyone please tell me how I could alter the code below to check if ever file contains the wordToChange and then apply the change it it does.

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

Clear-Content log.txt

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


If((Get-Content $_.FullName).Contains($wordToFind))
{
    Add-Content log.txt $_.FullName
    (Get-Content $_.FullName) | 
     ForEach-Object { $_ -replace $wordToFind , $wordToReplace } | 
     Set-Content $_.FullName
}



}

Thank you!

like image 312
John Walker Avatar asked Sep 05 '13 10:09

John Walker


2 Answers

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
}
like image 178
Get-Tek Avatar answered Oct 12 '22 19:10

Get-Tek


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.

like image 44
Richard Avatar answered Oct 12 '22 21:10

Richard