Powershell,使用contains来检查文件是否包含某个单词

Joh*_*ker 5 powershell

我正在尝试创建一个powershell脚本,它查看给定目录下的所有文件和文件夹,然后将.properties文件中给定单词的所有实例更改为另一个给定单词的实例.

我在下面写的内容确实如此,但是我的版本控制注意到每个文件中的更改,无论它是否包含要更改的单词的实例.为了解决这个问题,我尝试在获取/设置内容之前检查文件中是否存在该单词(如下所示)但是它告诉我[System.Object []]不包含名为'Contains'的方法.我认为这意味着$ _是一个数组所以我试图创建一个循环来遍历它并一次检查每个文件,但它告诉我它无法索引到System.IO.FileInfo类型的对象.

任何人都可以告诉我如何更改下面的代码,以检查文件是否包含wordToChange然后应用它所做的更改.

$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
}



}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ric*_*ard 17

试试这个:

$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
}

}
Run Code Online (Sandbox Code Playgroud)

这会将文件的内容放入一个数组中,$file然后检查每一行的单词.每行结果($true/ $false)都放入一个数组中$containsWord.然后检查该数组以查看该单词是否被找到($True变量存在); 如果是的话那就if loop运行了.