指定されたディレクトリ内のPATTERNを含むすべてのファイルを検索し、PATTERNを強調表示してドキュメントの関連行を印刷し、PATTERNを指定されたREPLACE単語に置き換えて、ファイルを保存するPowerShellスクリプトに取り組んでいます。したがって、実際にファイルを編集します。
Windowsがファイルがすでに開いていることについて文句を言うので、ファイルを変更するためにそれを取得できないことを除いて。私はこれを解決するためにいくつかの方法を試しましたが、問題にぶつかり続けます。おそらく誰かが助けることができます:
param(
[string] $pattern = ""
,[string] $replace = ""
,[string] $directory ="."
,[switch] $recurse = $false
,[switch] $caseSensitive = $false)
if($pattern -eq $null -or $pattern -eq "")
{
Write-Error "Please provide a search pattern." ; return
}
if($directory -eq $null -or $directory -eq "")
{
Write-Error "Please provide a directory." ; return
}
if($replace -eq $null -or $replace -eq "")
{
Write-Error "Please provide a string to replace." ; return
}
$regexPattern = $pattern
if($caseSensitive -eq $false) { $regexPattern = "(?i)$regexPattern" }
$regex = New-Object System.Text.RegularExpressions.Regex $regexPattern
function Write-HostAndHighlightPattern([string] $inputText)
{
$index = 0
$length = $inputText.Length
while($index -lt $length)
{
$match = $regex.Match($inputText, $index)
if($match.Success -and $match.Length -gt 0)
{
Write-Host $inputText.SubString($index, $match.Index) -nonewline
Write-Host $match.Value.ToString() -ForegroundColor Red -nonewline
$index = $match.Index + $match.Length
}
else
{
Write-Host $inputText.SubString($index) -nonewline
$index = $inputText.Length
}
}
}
Get-ChildItem $directory -recurse:$recurse |
Select-String -caseSensitive:$caseSensitive -pattern:$pattern |
foreach {
$file = ($directory + $_.FileName)
Write-Host "$($_.FileName)($($_.LineNumber)): " -nonewline
Write-HostAndHighlightPattern $_.Line
%{ Set-Content $file ((Get-Content $file) -replace ([Regex]::Escape("[$pattern]")),"[$replace]")}
Write-Host "`n"
Write-Host "Processed: $($file)"
}
この問題は、コードの最後のブロック内のGet-ChildItem呼び出しで発生します。もちろん、そのブロック内のコードの一部は、問題を修正して停止しようとしたために少し混乱していますが、スクリプトのその部分の意図を覚えておいてください。コンテンツを取得し、単語を置き換えてから、変更したテキストを取得したファイルに保存します。
どんな助けでも大歓迎です。