【问题标题】:Powershell creating pscustomobject objectPowershell 创建 pscustomobject 对象
【发布时间】:2021-12-06 13:32:07
【问题描述】:

我需要帮助解决一些我真的不知道的事情。我有一个包含大量这些 ID 的文件

我需要在 powershell 中创建一个 json 有效负载,使其看起来像这样包含这些 ID 中的每一个

{
  "assetIds": [
    "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "f86354c4-8e69-4cee-b85c-11b9534019e0",
    "6829c1ad-17d8-4d9c-93c7-2a4b6acfc201"
  ],
  "sendNotification": true
}

【问题讨论】:

    标签: json powershell pscustomobject


    【解决方案1】:

    相当简单:

    # define object
    $object = [pscustomobject]@{
      assetIds = @(
        Get-Content path\to\file.txt
      ) -as [string[]]
      sendNotification = $true
    }
    
    # convert to JSON
    $object |ConvertTo-Json
    

    @()(“子表达式运算符”)确保assetIds 属性的值始终是一个数组(即使Get-Content 返回 0 或仅返回 1 个 ID)

    -as [string[]] 转换可防止 PowerShell 序列化可能已由 Get-Content 附加到字符串的扩展属性

    【讨论】:

    • 这正是我正在寻找的。不过,问题是,我如何删除其余字段。我只想查看值字段“assetIds”中的内容:[ {“value”:“4a507ef9-185b-461a-ad8d-7f3dbd91da0c”,“PSPath”:“C:\\temp\\assets.txt” ,“PSParentPath”:“C:\\temp”,“PSChildName”:“assets.txt”,“PSDrive”:“C”,“PSProvider”:“Microsoft.PowerShell.Core\\FileSystem”,“ReadCount”: 1 },
    • 找到了,谢谢:)
    • @Hein 有几种解决方法,但最简单的方法是将结果数组转换为[string[]](我已经更新了答案)
    • 哇,你太棒了!!!非常感谢你
    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 2018-03-10
    • 1970-01-01
    • 2020-08-25
    • 2017-12-01
    • 2018-04-19
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多