且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-25 12:53:22

试试这个:

$directoryToTarget=$args[0]$wordToFind=$args[1]$wordToReplace=$args[2]清除内容日志.txtGet-ChildItem -Path $directoryToTarget -Filter *.properties -Recurse |{ !$_.PSIsContainer } |%{$file = Get-Content $_.FullName$containsWord = $file |%{$_ -匹配 $wordToFind}如果($containsWord -包含 $true){添加内容 log.txt $_.FullName($文件) |ForEach-Object { $_ -replace $wordToFind , $wordToReplace } |设置内容 $_.FullName}}

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

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!

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.