1

Basically, I have a .bas file that I am looking to update. Basically the script requires some manual configuration and I don't want my team to need to reconfigure the script every time they run it. What I would like to do is have a tag like this

<BEGINREPLACEMENT>
'MsgBox ("Loaded")


ReDim Preserve STIGArray(i - 1)
ReDim Preserve SVID(i - 1)

STIGArray = RemoveDupes(STIGArray)
SVID = RemoveDupes(SVID)
<ENDREPLACEMENT>

I am kind of familiar with powershell so what I was trying to do is to do is create an update file and to replace what is in between the tags with the update. What I was trying to do is:

$temp = Get-Content C:\Temp\file.bas
$update = Get-Content C:\Temp\update
$regex = "<BEGINREPLACEMENT>(.*?)<ENDREPLACEMENT>"

$temp -replace $regex, $update
$temp | Out-File C:\Temp\file.bas

The issue is that it isn't replacing the block of text. I can get it to replace either or but I can't get it to pull in everything in between.

Does anyone have any thoughts as to how I can do this?

4
  • 1
    You need to use -Raw when reading files in and a "(?s)<BEGINREPLACEMENT>.*?<ENDREPLACEMENT>" regex. Also, use escape dollars in dynamic replacement $temp -replace $regex, $update.Replace('$', '$$') Commented Dec 10, 2019 at 14:29
  • Yupp that was it (Reading it in as -Raw and updating regex)! Im not sure why the regex needs to be different though doesn't mine look for anything in between the two tags? Commented Dec 10, 2019 at 14:52
  • The . does not match a newline char by default. Commented Dec 10, 2019 at 14:53
  • Got it. Well that completely solved my issue. Thanks so much! Commented Dec 10, 2019 at 14:58

1 Answer 1

1

You need to make sure you read the whole files in with newlines, which is possible with the -Raw option passed to Get-Content.

Then, . does not match a newline char by default, hence you need to use a (?s) inline DOTALL (or "singleline") option.

Also, if your dynamic content contains something like $2 you may get an exception since this is a backreference to Group 2 that is missing from your pattern. You need to process the replacement string by doubling each $ in it.

$temp = Get-Content C:\Temp\file.bas -Raw
$update = Get-Content C:\Temp\update -Raw
$regex = "(?s)<BEGINREPLACEMENT>.*?<ENDREPLACEMENT>"
$temp -replace $regex, $update.Replace('$', '$$')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.