我已经构建了一系列JSON文件,这些文件将被各种模块和脚本引用。在JSON中,我引用了脚本/模块所在的PowerShell实例(和作用域)中已经存在的变量。问题是,ConvertFrom-Json中引用的变量似乎导入了一个文字,因此变量一旦进入会话就不会展开。
当你浏览下面的test.ps1时,你会发现我一直在尝试做什么,以及我的目标是什么(我希望如此)。如果没有,请让我解释。有时候我并不擅长传达我想要的东西!
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 @ConnectionParamstest.json
{
"Server" : {
"connectionType" : "PSSession",
"connectionSubType" : "ServerType",
"securityLevel" : "Level1",
"connectionParameters" : {
"ComputerName" : "ServerNameHere",
"ErrorAction" : "Stop",
"Credential" : "$Creds"
}
}
}发布于 2017-02-12 07:29:38
对于简单的值,您可以像这样强制变量epxansion:
$response = Invoke-WebRequest -Uri ... | Select-Object -Expand Content
$json = $ExecutionContext.InvokeCommand.ExpandString($response) |
ConvertFrom-Json但是,这通常不适用于像PSCredential对象这样的复杂数据类型。它们将作为它们的字符串表示形式插入。
如果您确切知道需要扩展哪个选项,可以使用Invoke-Expression
$json = Invoke-WebRequest -Uri ... |
Select-Object -Expand Content |
ConvertFrom-Json
$json.Server.connectionParameters.Credential = Invoke-Expression $json.Server.connectionParameters.Credential除此之外,我不认为PowerShell有什么内置的东西可以做你想要的。此外,我看不到从网络加载复杂数据结构然后填充(任意?)其中包含局部变量的部分会很有用。
https://stackoverflow.com/questions/42181610
复制相似问题