我想创建一个PowerShell脚本看起来通过所有文件和文件夹给定的目录,然后它的变化在.properties文件中给定单词的所有实例到另一个定单词的实例之下。
我已经写在下面做这个但是我的版本控制应注意的每一个文件的改变,无论它是否包含更改单词的一个实例。为了解决这个问题我试图把一个检查,看看这个词是否存在未在文件之前,我获得/设置内容(如下图所示),但它告诉我,[System.Object的[]不包含命名方法“包含”。我以为这意味着,$ _是一个数组,所以我试图创建一个循环都要经过它,并在同一时间检查每个文件但它告诉我,这是无法索引类型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
}
}
谢谢!
尝试这个:
$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
}
}
这将使该文件的内容到一个数组$file
然后检查每一行字。每个线导致($true
/ $false
)放入到一个数组$containsWord
。然后将阵列检查,看看是否该字被发现($True
变量存在);如果是这样,则if loop
运行。
简体包含条款
$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
}
检查文件的最简单方法包含单词
如果我们看Get-Content
结果我们发现字符串的System.Array。所以,我们可以这样做在System.Linq的.NET中:
content.Any(s => s.Contains(wordToFind));
在PowerShell中,它看起来像:
Get-Content $filePath `
| %{ $res = $false } `
{ $res = $res -or $_.Contains($wordToFind) } `
{ return $res }
其结果是,我们可以在小命令,文件路径的PARAMS和含字汇总并使用它。还有一:我们可以使用正则表达式与-match
代替Contains
,所以这将是更加灵活。