PowerShell:设置内容存在“文件已在使用中”问题

Eli*_*son 3 powershell scripting replace locking file

我正在使用一个PowerShell脚本来查找给定目录内所有带有PATTERN的文件,打印出文档的相关行并突出显示PATTERN,然后用提供的REPLACE单词替换PATTERN,然后将文件保存回去。因此,它实际上是在编辑文件。

除了我无法更改文件外,因为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)"
    }
Run Code Online (Sandbox Code Playgroud)

问题位于代码的最后一块内,就在Get-ChildItem调用处。当然,由于我试图解决问题然后停止运行,该块中的某些代码现在有些混乱,但请记住脚本那部分的意图。我想获取内容,替换单词,然后将更改后的文本保存回我从中获取的文件中。

任何帮助将不胜感激。

yam*_*men 5

删除了我以前的答案,将其替换为:

Get-ChildItem $directory -recurse:$recurse
foreach {        
    $file = ($directory + $_.FileName)

    (Get-Content $file) | Foreach-object {
        $_ -replace ([Regex]::Escape("[$pattern]")),"[$replace]")
    } | Set-Content $file
}
Run Code Online (Sandbox Code Playgroud)

注意:

  • 用圆括号括住,Get-Content以确保将文件一口吃完(然后关闭)。
  • 管道传递到后续命令,而不是内联。
  • 您的某些命令已删除,以确保它是一个简单的测试。


小智 0

只是一个建议,但您可以尝试查看参数代码块的文档。有一种更有效的方法可以确保在您需要时输入参数,并在用户不需要时抛出错误消息。

关于抛出:http ://technet.microsoft.com/en-us/library/dd819510.aspx 关于功能高级参数:http://technet.microsoft.com/en-us/library/dd347600.aspx

然后关于一直使用 Write-Host:http://powershell.com/cs/blogs/donjones/archive/2012/04/06/2012-scripting-games-commentary-stop-using-write-host.aspx