Powershell retrieving a variable from a text file

前端 未结 3 1121
渐次进展
渐次进展 2021-02-01 05:08

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
         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 05:46

    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]
    
    }
    

提交回复
热议问题