Skip to content

Add-LinesToFile insert can fail with "Unable to move the replacement file" after previewing changes #55

Description

@sharpninja

Summary

Add-LinesToFile in PowerShell.MCP 1.11.0 intermittently fails when inserting a multi-line block into an existing file on Windows. The cmdlet prints the normal changed-line preview, then reports:

Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name.

A subsequent read confirms the target file was not changed.

Environment

PowerShell.MCP: 1.11.0
PowerShell: 7.6.3 Core
OS: Microsoft Windows 10.0.26200
Platform: Win32NT
Module path: C:\Users\kingd\OneDrive\Documents\PowerShell\Modules\PowerShell.MCP\1.11.0\PowerShell.MCP.psd1
Workspace file path: F:\GitHub\McpServer\tests\Build.Tests\WarningSuppressionValidationTargetTests.cs

Failing operation

This failed while inserting a multi-line C# test method into an existing file:

Add-LinesToFile 'tests\Build.Tests\WarningSuppressionValidationTargetTests.cs' -LineNumber 217 -Content $var1

The command displayed a diff-like preview showing the inserted block at line 217, then emitted the replacement-file move error above. Running Show-TextFiles immediately afterward showed the original file unchanged.

A similar insert failure occurred earlier in the same session while inserting class constants into:

tests\Build.Tests\MigrationAssemblyObsoleteWarningTests.cs

Workaround that succeeded

Replacing the existing line with a block that included the original line worked:

Update-LinesInFile 'tests\Build.Tests\WarningSuppressionValidationTargetTests.cs' -LineRange 217 -Content $var1

Non-repro on a tiny file

A small temp-file insert succeeded, so this may be related to existing file size/state, path, locking, or replacement-file handling rather than all Add-LinesToFile -LineNumber calls:

$tempPath = Join-Path 'C:\tmp' ('psmcp-add-lines-repro-' + [Guid]::NewGuid().ToString('N') + '.txt')
Add-LinesToFile $tempPath -Content "line 1`r`nline 2`r`nline 3`r`n"
Add-LinesToFile $tempPath -LineNumber 2 -Content "inserted a`r`ninserted b`r`n"

Expected

Add-LinesToFile -LineNumber should either atomically insert the lines or return a diagnostic with the underlying source/target temp paths and the original IO exception.

Actual

The cmdlet previews the intended change, then fails to move the replacement file over the original and leaves the target unchanged. The error does not expose enough path/exception detail to diagnose whether this is a lock, cross-volume move, temp path issue, retry problem, or another Windows filesystem condition.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions