Extract part of text in a variable

Asked

Viewed 136 times

0

I am creating a script to backup some directories via powershell, but for a certain directory, I want to access a file, read a line and return a string with part of the line.

XPTO file has the following structure:

;===============================================================
;--------------------AMBIENTE DE PRODUÇÃO-----------------------
;===============================================================

[C4P12LEAD]
SourcePath=E:\Outsourcing\Clientes\c4p12lead\apo\20180828
RootPath=E:\Outsourcing\Clientes\c4p12lead\protheus-data
CtreeRootPath=E:\Outsourcing\Clientes\c4p12lead\protheus-data
StartPath=\system\
x2_path=
RpoDb=top
RpoLanguage=por
RpoVersion=120
LocalFiles=ctree
Trace=0

I need to return the path of the line that contains Sourcepath: SourcePath =E:\Outsourcing\Clientes\c4p12lead\apo\20180828

And put that path in a Sourveapo variable: E:\Outsourcing\Clientes\c4p12lead\apo\20180828

At the end of the process the $Sourveapo variable needs to have the content E:\Outsourcing\Clientes\c4p12lead\apo\20180828

How am I gonna do that?

1 answer

1

Break the text into lines, search for its tag and then take the value by text position.

$text = "
;===============================================================
;--------------------AMBIENTE DE PRODUÇÃO-----------------------
;===============================================================

[C4P12LEAD]
SourcePath=E:\Outsourcing\Clientes\c4p12lead\apo\20180828
RootPath=E:\Outsourcing\Clientes\c4p12lead\protheus-data
CtreeRootPath=E:\Outsourcing\Clientes\c4p12lead\protheus-data
StartPath=\system\
x2_path=
RpoDb=top
RpoLanguage=por
RpoVersion=120
LocalFiles=ctree
Trace=0";

$token="SourcePath"
$extractedValue = (($text -split [System.Environment]::NewLine) | where { $_ -Like "$token*" }).Substring("$token=".Length);
Write-Host $extractedValue
  • Thank you Bruno.

  • 1

    From what you’re saying, it seems to be the case mark an answer as accepted. Here we do not write "solved" in the question. If you have an answer that really helped you, mark it as accepted. If you came to the solution on your own, put in the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.