200mg
200mg

Reputation: 531

Select String From Text File and Create variable

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

Upvotes: 1

Views: 697

Answers (2)

mklement0
mklement0

Reputation: 437238

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.

Upvotes: 0

AdminOfThings
AdminOfThings

Reputation: 25001

$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.

Upvotes: 1

Related Questions