tags:

views:

44

answers:

1

I am trying to do something very simple in powershell

  1. Reading the contents of a file
  2. Manipulation some string
  3. Saving the modified test back to the file

    function Replace { $file = Get-Content C:\Path\File.cs $file | foreach {$_ -replace "document.getElementById", "$"} |out-file -filepath C:\Path\File.cs }

I have tried Set-Content as well.

I always get unautorized exception. I can see the $file has the file content, error is coming while writing the file.

Any help is appreciated.

Ben

+2  A: 

This is likely caused by the Get-Content cmdlet that gets a lock for reading and Out-File that tries to get its lock for writing. Similar question is here: Powershell: how do you read & write I/O within one pipeline?

So the solution would be:

${C:\Path\File.cs} = ${C:\Path\File.cs} | foreach {$_ -replace "document.getElementById", '$'}
${C:\Path\File.cs} = Get-Content C:\Path\File.cs | foreach {$_ -replace  "document.getElementById", '$'}

$content = Get-Content C:\Path\File.cs | foreach {$_ -replace "document.getElementById", '$'}
$content | Set-Content C:\Path\File.cs

Basically you need to buffer the content of the file so that the file can be closed (Get-Content for reading) and after that the buffer should be flushed to the file (Set-Content, during that write lock will be required).

stej
It worked. Thanks. Now I feel stupid for asking this :) but thanks.I did read about this but since I was piping everything in one statement it gave me error as the lock was not released.Cool!!
Ben