0

I'm trying to replace multiple strings for new ones, always in the same file. This would be an example. This give me no problems.

(get-content modTags.bas) | %{$_ -replace  "rng_origin.Offset(ColumnOffset:=1)", "rng_origin.Offset(ColumnOffset:=0)"} | set-content modTags.bas

But if I repeat this line in the script (in fact, i must do it like 20 times) I get the error that the file is currently in use.

I have tried to put (set-content) like in (get-content), but it seems it doesn't works for only allow parameters in the first command in the pipeline.

I already know how to "bypass" this error.

By typing all my replacements inline it works (or continue the code in a new line) like this.

(get-content modTags.bas) | %{$_ -replace "X","Y" `
 -replace "A","B"} | set-content modTags.bas

So this is a question about why set-content keeps the file occupy for new query in the same script and how can it be avoided? With get-content it easy with the () solution, and I was kinda expecting something similar for set-content.

And second. Could you suggest any better alternative for replacing multiple strings for different ones and save it in the same file (not creating a file.new.txt file.old.txt or something like that)

Thanks!

e270889o
  • 33
  • 2
  • Do you need a one liner? Store it in a variable? – guiwhatsthat Oct 23 '17 at 11:41
  • A possiblity (just a guess) might be that individual calls of set-content just happen too fast and the filehandle needs a tiny bit of time to close after each operation. To try this you could set put a `Start-Sleep -Milliseconds 100` after each set-content. Not to keep this in the final script, just to find the cause. Btw, is there any reason why you use | and % instead of just `(get-content modTags.bas) -replace ....`? – whatever Oct 23 '17 at 11:46
  • Usually you probably do what guiwhatsthat suggested and store the contents of the file in a variable, do all replacements on that and write to file only once at the end. – whatever Oct 23 '17 at 12:10
  • I just noticed I have to tweak special characters for the search to work, I will edit it but thats not the topic here. I will test what you said later. But I don't know if it is possible. The text file is like 1000 lines long. Can powershell put a hole document into a variable (preserving format, like spaces) and then return it to a file like nothing has happend but the replacement of words? Thanks! – e270889o Oct 23 '17 at 12:14
  • 1
    @e270889o I had to do something similar on a 5,000 line long kix script. I also ran into similar issues as you. Storing the file in a variable, and setting that equal to the replacement fixed all my issues. – Nick Oct 23 '17 at 12:17
  • Seems here explains what you said. I will test it tomorrow and post the results https://stackoverflow.com/questions/7976646/powershell-store-entire-text-file-contents-in-variable – e270889o Oct 23 '17 at 12:19

0 Answers0