在 PowerShell 中提取 JSON 变量属性并将变量扩展为其值

问题描述 投票:0回答:1

我在 PowerShell 中创建了一个 JSON 文件,其中包含相关文件的属性。当我检索属性时,我希望提取的变量扩展到其值。

JSON 文件包含通过 Export-Excel 格式化数据并将数据插入到创建的 Excel 文件中的信息。

我的目标是循环遍历 JSON 文件并提取所有信息来创建电子表格。

这是 JSON 文件的片段:

{
    "ClientMatters_Count": {
       "Var":   "$ClientMattersList",
       "File":  "D:\\TFS\\ProjectND\\ImportExport\\Import\\Export\\ClientMattersListCount.csv",
    },
    "DocTypes_Count": {
      "Var":   "$DocTypesList",
      "File":  "$DocTypesListCountCsv",
    }
}

当我提取 ClientMatters_Count.File 时,它会提取字符串并且它可以工作。虽然这有效,但对我来说并不理想。

我想让 DocTypes_Counts.File 变量扩展到它的值。

例如,

Defined in PowerShell:
$DocTypesListCountCsv = "D:\TFS\Project\ImportExport\Import\Export\DocTypeListCount.csv"

When I read the JSON file, 
ClientMatters.DocType_Counts.File gives me $DocTypesListCountCsv

I would like it to give me:
D:\TFS\Project\ImportExport\Import\Export\DocTypeListCount.csv

*.Var 属性将插入到 Excel 电子表格中,并在运行时创建它们的值。

$Nd_ClientMattersList.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

我尝试过对变量进行类型转换并删除字符串,但没有成功。

建议的答案是这样的:

$ExcelConfig.DocTypes_Count.File

$Nd_DocTypesListCountCsv

Get-Variable -Name $ExcelConfig.DocTypes_Count.File -ValueOnly

Get-Variable: Cannot find a variable with the name '$Nd_DocTypesListCountCsv'.
json powershell
1个回答
0
投票

您可以使用

ExpandString
方法来计算存储在字符串中的变量表达式:

$DocTypesListCountCsv = "D:\TFS\Project\ImportExport\Import\Export\DocTypeListCount.csv"

$json = @'
{
    "ClientMatters_Count": {
       "Var":   "$ClientMattersList",
       "File":  "D:\\TFS\\ProjectND\\ImportExport\\Import\\Export\\ClientMattersListCount.csv",
    },
    "DocTypes_Count": {
      "Var":   "$DocTypesList",
      "File":  "$DocTypesListCountCsv",
    }
}
'@ | ConvertFrom-Json

$ExecutionContext.InvokeCommand.ExpandString($json.DocTypes_Count.File)
© www.soinside.com 2019 - 2024. All rights reserved.