Michael B
Michael B

Reputation: 12228

How to expand a variable stored in a text file

Given the following bit of json saved in a file.

{
    "Username":  "userbob",
    "Password":  "$password"
}

How can I read that file (to a variable), and expand the $password variable?

Upvotes: 1

Views: 345

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

You could read it into a (single) string and call ExpandString():

$password = "s3cr3tz"

# Read into string variable:
$jsonTemplate = Get-Content -Raw

# Expand string
$json = $ExecutionContext.InvokeCommand.ExpandString($jsonTemplate)

This will cause the parser to expand the string:

PS C:\> $json |ConvertFrom-Json

Username Password
-------- --------
userbob  s3cr3tz

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58931

Read the file using the Get-Content cmdlet, convert it using ConvertFrom-Json and finally select the password.

Get-Content "c:\yourjsonfile.json" | ConvertFrom-Json | select -expand Password

Upvotes: 0

Related Questions