PowerShell: Set-Content having issues with “file already in use”

Question:

I’m working on a PowerShell script that finds all the files with PATTERN within a given DIRECTORY, prints out the relevant lines of the document with the PATTERN highlighted, and then replaces the PATTERN with a provided REPLACE word, then saves the file back. So it actually edits the file.

Except I can’t get it to alter the file, because Windows complains about the file already being open. I tried several methods to solve this, but keep running into the issue. Perhaps someone can help:

The issue is located within the final block of code, right at the Get-ChildItem call. Of course, some of the code in that block is now a bit mangled due to me trying to fix the problem then stopping, but keep in mind the intent of that part of the script. I want to get the content, replace the words, then save the altered text back to the file I got it from.

Any help at all would be greatly appreciated.

Answer:

Removed my previous answer, replacing it with this:

Note:

  • The parentheses around Get-Content to ensure the file is slurped in one go (and therefore closed).
  • The piping to subsequent commands rather than inlining.
  • Some of your commands have been removed to ensure it’s a simple test.

Source:

PowerShell: Set-Content having issues with “file already in use” by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply