Powershell parses a colon file of properties

If I have a .properties file containing directories (containing colons):

some_dir=f:\some\dir\etc
another_dir=d:\dir\some\bin

and then use ConvertFrom-StringData to convert the Key = Value pair from the specified properties file to a hash table:

$props_file = Get-Content "F:\dir\etc\props.properties"
$props = ConvertFrom-StringData ($props_file)
$the_dir = $props.'some_dir'
Write-Host $the_dir

Powershell throws an error (doesn't like colons):

ConvertFrom-StringData : Cannot convert 'System.Object[]' to the type 'System.String'    required by parameter 'StringData'. Specified method is not supported.
At line:3 char:32
+ $props = ConvertFrom-StringData <<<<  ($props_file)
+ CategoryInfo          : InvalidArgument: (:) [ConvertFrom-StringData],     ParameterBindingException
+ FullyQualifiedErrorId :     CannotConvertArgument,Microsoft.PowerShell.Commands.ConvertFromStringDataCommand

How to get around this? I would like to be able to just reference directories using. Designations:

$props.'some_dir'
+4
source share
3 answers

, . , ConvertFrom-StringData, , , . , , escape-.

, :

# Reading file as a single string:
$sRawString = Get-Content "F:\dir\etc\props.properties" | Out-String

# The following line of code makes no sense at first glance 
# but it only because the first '\\' is a regex pattern and the second isn't. )
$sStringToConvert = $sRawString -replace '\\', '\\'

# And now conversion works.
$htProperties = ConvertFrom-StringData $sStringToConvert

$the_dir = $htProperties.'some_dir'
Write-Host $the_dir
+7

- .

$props = @{}
GC "F:\dir\etc\props.properties" | %{$props.add($_.split('=')[0],$_.split('=')[1])}
+3

ConvertFrom-StringDataexpects a string, and you pass it an array of Get-Contentcmdlets. Change $props_fileto:

$props_file = (Get-Content "F:\dir\etc\props.properties") | Out-String

and you will get another error:

ConvertFrom-StringData : parsing "f:\some\dir\etc" - Unrecognized escape sequence \s.

You can get around it like this:

$props_file = Get-Content "F:\dir\etc\props.properties"
$props = @{}
$props_file | % {
    $s = $_ -split "="
    $props.Add($s[0],$s[1])
}
$the_dir = $props.'some_dir'
Write-Host $the_dir

Result:

f:\some\dir\etc
+2
source

Source: https://habr.com/ru/post/1543986/


All Articles