31

Is there a way to read a text file C:\test.txt and retrieve a particular value?

ie file looks like this:

serverName=serv8496
midasServer=serv8194

I want to set the value of a variable in my script in some way from this file eg:

$MidasServer= (from file midasServer value)

I will not know the line number where the reference is.

Any way to do this?

5 Answers 5

34

Yes, read the file, split each line and assign the split result to the Name and Value parameters:

Get-Content file.txt | Foreach-Object{
   $var = $_.Split('=')
   New-Variable -Name $var[0] -Value $var[1]
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works for me, but I keep getting an error saying that Name could not be created because it is an empty string. Why is that?
19

If that is exactly how your file appears i.e. a list of key value pairs denoted with a equals sign then you should have a look at ConvertFrom-StringData which

converts a string that contains one or more key and value pairs into a hash table. Because each key/value pair must be on a separate line, here-strings are often used as the input format.

So if a text file contained just the data in your example you could do this to create a hashtable

$Path = "C:\temp\test.txt"
$values = Get-Content $Path | Out-String | ConvertFrom-StringData
$values.midasServer

Where the $values.midasServer would have the value serv8194. No need to know where the properties are in respect to the file. Your input file can also have varying leading and trailing space around the equals sign which will give the exact same result.

Depending on your use case you can take that one step farther and create a custom object from that hashtable

New-Object -TypeName pscustomobject -Property $values

If you have at least PowerShell v3 or higher you can simplify the process (assuming you want a custom psobject)

$values = [pscustomobject](Get-Content $Path -Raw | ConvertFrom-StringData)
$values.midasServer

1 Comment

wow this answer was simple and straightforward - great for other non-techie admins who have to update key/values later without breaking the main script... :D
8

This is an improvement to the Shay Levy's answer. It does the following.

  1. It ignores commented lines and new lines in the file.txt before start processing the file. So it resolves the error saying that name could not be created because it is an empty string.
  2. It splits only on the first occurrence of the character "=". Therefore you can use any characters in the value field.
  3. It performs Trim() operation in order to remove space characters from the beginning and end of the variable/property. Therefore "VARIABLE=VALUE" and "VARIABLE = VALUE" in the file.txt returns the same.
  4. Set the scope of new variables to "Script". Variables created in the script scope are accessible only within the script file or module they are created in. Other options are Global, Local and Private. You can find a variable scope reference here.
Get-Content file.txt | Where-Object {$_.length -gt 0} | Where-Object {!$_.StartsWith("#")} | ForEach-Object {

    $var = $_.Split('=',2).Trim()
    New-Variable -Scope Script -Name $var[0] -Value $var[1]

}

1 Comment

What about line endings (windows CRLF vs. linux LF) is PS able to handle both?
0

This was successful for me:

(input file = filename.txt)
[string] $person 'Joe'
[int] $age 50
[datetime] $dob '06/11/1971'

(commands)
Get-Content filename.txt | ForEach-Object {
    $invar = $_.Split(" ").Trim()
    Invoke-Expression (Invoke-Command -ScriptBlock {
        $($invar[0])+$($invar[1])+'='+$($invar[2])
        } )
}

If you know there's a "value", that will contain spaces, i.e. "person "Joe B", just join the values, like so...

Replace this:
        $($invar[0])+$($invar[1])+'='+$($invar[2])

With this:
        $($invar[1])+$($invar[2])+'='+ (-join $($invar[3]),$($invar[4]),$($invar[5]) )

Comments

0

I had the same problem actually and we use an approach looks like

$serverName = (Get-Content .\YourFilename).split()[0].split("=")[1]

Hope this helps guys

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.