Reputation: 9
I've built a series of JSON files that will be referenced by various modules and scripts. In the JSON, I make references to variables that will already exist in the PowerShell instance (and scope) that the script/module is in.
The problem is that the variables referenced in the ConvertFrom-Json
appear to imported a literal, so the variables aren't expanding once they are in the session.
When you glance at test.ps1
below, you'll see what I've tried to do, and what my goal is (I hope). If not, please ask me to explain. Sometimes I'm not the best at conveying what I'm after!
test.ps1
:
# The following Invoke-WebRequest just pulls in the JSON in this Gist
$JSON = Invoke-WebRequest -Uri 'https://gist.githubusercontent.com/mpearon/a8614d73793c582760a6e2b9668d4f62/raw/2000ded35b6c8f9dd790f36a3169810acd5e3bdf/test.json' |
ConvertFrom-Json
$ConnectionParams = @{
ComputerName = $JSON.Server.connectionParameters.ComputerName
ErrorAction = $JSON.Server.connectionParameters.ErrorAction
Credential = $JSON.Server.connectionParameters.Credential
}
Enter-PSSession @ConnectionParams
test.json
:
{
"Server" : {
"connectionType" : "PSSession",
"connectionSubType" : "ServerType",
"securityLevel" : "Level1",
"connectionParameters" : {
"ComputerName" : "ServerNameHere",
"ErrorAction" : "Stop",
"Credential" : "$Creds"
}
}
}
Upvotes: 0
Views: 1589
Reputation: 200203
For simple values you could force variable epxansion like this:
$response = Invoke-WebRequest -Uri ... | Select-Object -Expand Content
$json = $ExecutionContext.InvokeCommand.ExpandString($response) |
ConvertFrom-Json
However, that usually won't work with complex data types like PSCredential
objects. Those would be inserted as their string representation.
If you know which option exactly you need expanded you could use Invoke-Expression
:
$json = Invoke-WebRequest -Uri ... |
Select-Object -Expand Content |
ConvertFrom-Json
$json.Server.connectionParameters.Credential = Invoke-Expression $json.Server.connectionParameters.Credential
Other than that I don't think PowerShell has something built-in that would do what you want. Besides, I fail to see where loading complex data structures from the network then filling (arbitrary?) parts of them with local variables would be useful.
Upvotes: 3