Powershell: read the file section in a variable

I am trying to create a kind of polyglot script. This is not a real polyglot, because it actually requires the execution of several languages, although it can be "downloaded" using Shell or Batch. I have this problem is not a problem.

I have a problem with a part of the Powershell built-in code that should be able to load the current file into memory and extract a specific section written in another language, store it in a variable, and finally pass it to the translator. I have an XML-like tag system that I use to mark sections of a file in a way that I hope will not conflict with any other language. Markers look like this:

lang_a_code # <{LANGB}> ... code in language B ... ... code in language B ... ... code in language B ... # <{/LANGB}> lang_c_code 

# are comment markers, but comment markers may vary depending on the language of the section.

The problem is that I cannot find a way to isolate only this section of the file. I can load the entire file into memory, but I cannot get the material between the tags. Here is my current code:

 @ECHO OFF SETLOCAL EnableDelayedExpansion powershell -ExecutionPolicy unrestricted -Command ^ $re = '(?m)^<{LANGB}^>(.*)^<{/LANGB}^>';^ $lang_b_code = ([IO.File]::ReadAllText(^'%0^') -replace $re,'$1');^ echo "${re}";^ echo "Contents: ${lang_b_code}"; 

Everything that I tried so far leads to the fact that the whole file is displayed in Contents , and not just the code between the markers. I tried different ways to avoid the characters used in markers, but this always leads to the same.

NOTE The use of ^ is required because the top-level interpreter is a batch that hangs on angle brackets and other random things.

+5
source share
1 answer

Since there is only one block, you can use regex

 $re = '(?s)^<{LANGB}^>(.*)^^.*^<{/LANGB}^>';^ 

but with the -match operator, and then access the text using the $matches[1] variable set as a result of -match .

So after regex declaration use

 [IO.File]::ReadAllText(^'%0^') -match $re;^ echo $matches[1]; 
+5
source

All Articles