ฉันกำลังทำงานกับสคริปต์ PowerShell ที่จะค้นหาไฟล์ทั้งหมดที่มี PATTERN ภายใน DIRECTORY ที่กำหนด พิมพ์บรรทัดที่เกี่ยวข้องของเอกสารโดยที่ PATTERN ไฮไลต์ไว้ จากนั้นแทนที่ PATTERN ด้วยคำ REPLACE ที่ให้มา จากนั้นจึงบันทึกไฟล์กลับ ดังนั้นจึงแก้ไขไฟล์ได้จริง
ยกเว้นว่าฉันไม่สามารถแก้ไขไฟล์ได้ เนื่องจาก 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 แน่นอนว่าโค้ดบางส่วนในบล็อกนั้นตอนนี้เสียหายเล็กน้อยเนื่องจากฉันพยายามแก้ไขปัญหาแล้วหยุดทำงาน แต่อย่าลืมคำนึงถึงจุดประสงค์ของส่วนนั้นของสคริปต์ด้วย ฉันต้องการรับเนื้อหา แทนที่คำ จากนั้นบันทึกข้อความที่แก้ไขกลับไปยังไฟล์ที่ฉันได้รับ
ความช่วยเหลือใด ๆ เลยจะได้รับการชื่นชมอย่างมาก