1

I have a text file containing a string I need to make a variable. I need the value for "file" to be retained as a variable. How can I capture this and make it a variable: "\APPSRV\I\Run\OPTI\CLIENT\20171031\25490175\Data\brtctybv\". This data will change per file, but it will retain the same format, it will start with \ and end with \

Example Text File

order_id = 25490175-brtctybv
file     = \\APPSRV\I\Run\OPTI\CLIENT\20171031\25490175\Data\brtctybv\
copies   = 1
volume   = 20171031-brtctybv
label    = \\domain.com\prodmaster\jobs\OPTI\CLIENT\Cdlab\somefile.file
merge    = \\APPSRV\I\Run\OPTI\CLIENT\20171031\25490175\mrg\25490175-brtctybv.MRG
FIXATE   = NOAPPEND
2
  • Do you mean "retained as the value of a variable"? Commented Mar 4, 2019 at 21:54
  • Yes, I need the selected string to be retained as the value of a variable. I'm having having a hard time trying to figure out how to grab that UNC path out of the text file. Commented Mar 4, 2019 at 22:02

2 Answers 2

1
$file = ((Get-Content -path file.txt) | Select-String -pattern "^file\s*=\s*(\\\\.*\\)").matches.groups[1].value
$file

See Regex Demo to see the regex in action. The .matches.groups[1].value is grabbing the value of capture group 1. The capture group is created by the () within the pattern. See Select-String for more information about the cmdlet.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks AoT, regex god
Thanks for the RegEx Demo update, very much appreciated
0

Regexes are powerful, but complex; sometimes there are conceptually simpler alternatives:

PS> ((Get-Content -Raw file.txt).Replace('\', '\\') | ConvertFrom-StringData).file

\\APPSRV\I\Run\OPTI\CLIENT\20171031\25490175\Data\brtctybv\
  • The ConvertFrom-StringData cmdlet is built for parsing key-value pairs separated by =

  • \ in the values is interpreted as an escape character, however, hence the doubling of \ in the input file with .Replace('\', '\\').

  • The result is a hash table (type [hashtable]); Get-Content -Raw - the input file read as a single string - is used to ensure that a single hash table is output); accessing its file key retrieves the associated value.

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.