How avoid \t being converted to Tab in Powershell

64 views Asked by At

I'm trying to retrieve a parameter value from a config a file.

(Get-Content C:\<ConfigFolder>\basic.conf | ConvertFrom-StringData)."FileLocation"

The value of the "FileLocation" is "C:\temp".

And, value printed on screen is;

"C:     emp"

Looks like "\t" is parsed as a Tab.

Is there a way avoid this and print the as original value as is?

File content is as below;

UpdatedTime="2024-03-26 09:55:00"
FileLocation="C:\temp"
1

There are 1 answers

0
mklement0 On BEST ANSWER

zett42 has provided the crucial pointer:

From the ConvertFrom-StringData help topic (emphasis added), as of PowerShell 7.4.x:

ConvertFrom-StringData supports escape character sequences that are allowed by conventional machine translation tools. That is, the cmdlet can interpret backslashes (\) as escape characters in the string data [...] You can also preserve a literal backslash in your results by escaping it with a preceding backslash, like this: \\. Unescaped backslash characters, such as those that are commonly used in file paths, can render as illegal escape sequences in your results.

Therefore, assuming that all \ characters in your input file are meant to be interpreted literally:

(Get-Content -Raw C:\<ConfigFolder>\basic.conf).Replace('\', '\\') |
  ConvertFrom-StringData).FileLocation

Note the use of -Raw with Get-Content to ensure that the file content is read in full, as a single, (typically) multiline string, which in turn ensures that ConvertFrom-StringData outputs a single [hashtable] instance.
(If, by contrast, you really mean to output a separate hashtable for each input line, omit -Raw).


Given that this escaping need may be inconvenient (and possibly somewhat unexpected, but that cannot be helped), it would be helpful if ConvertFrom-StringData itself supported verbatim (literal) parsing by way of an opt-in:

  • GitHub issue #20418 asks for just that, by way of a future -Raw switch. This enhancement has been green-lit, but is yet to be implemented.