我有一个脚本,它在订阅中的Azure VM列表上运行,并 for each VM输出一个文件,下面是其内容的一个示例:

Value[0]        : 
  Code          : ComponentStatus/StdOut/succeeded
  Level         : Info
  DisplayStatus : Provisioning succeeded
  Message       :     Directory: C:\variasuit_windows\HARMOR\windows_server\package


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
d-----       12/23/2023   5:10 AM                HARMOR                                                                
"Server Name","GPO_HARMOR","BIOMEDIC_AGENT","EDWARD_STATUS","SENSOR_STATUS","SENTINEL_STATUS"
"AZ-TSTAPP1D","OK","OK","OK","OK","KO"


Value[1]        : 
  Code          : ComponentStatus/StdErr/succeeded
  Level         : Info
  DisplayStatus : Provisioning succeeded
  Message       : 
Status          : Succeeded
Capacity        : 0
Count           : 0

我想使用PowerShell解析该文件,以获得以下代码行:

"AZ-TSTAPP1D","OK","OK","OK","OK","KO"

然后将该值从每个文件收集到另一个txt文件,得到如下所示

"AZ-TSTAPP1D","OK","OK","OK","OK","KO"
"AZ-TSTAPP2D","OK","KO","KO","KO","KO"
"AZ-TSTAPP3D","OK","OK","OK","OK","KO"

I tried to get the content of this specific line but I found out that line number can change from a file to another
I tried this:

        $scriptResult = Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -CommandId 'RunPowerShellScript' -ScriptPath $scriptPath

        $scriptResult | Out-File $tempFile
        $contentFromFile = Get-Content -Path $tempFile
        $line12 = $contentFromFile | Select-Object -Index 11
        $line12 | Out-File $outputFile -Append
        Remove-Item $tempFile

Any help please?
Thanks

推荐答案

概括地说:

  • 我不知道Invoke-AzVMRunCommand是否能够转发(序列化)对象,但如果是的话,您最好对对象进行操作,而不是对其for-display string representations进行操作.

至于您的代码:

  • 您不需要临时文件,可以使用带有-Stream参数的Out-String逐行获取For-Display格式化表示;如果Invoke-AzVMRunCommand只发出text,那么您甚至不需要它.

  • 您可以使用带有regex-match运算符来筛选出感兴趣的行.

  • 可以使用>> redirection操作符作为管道连接到Out-File -Append的快捷方式.

@($scriptResult | Out-String -Stream) -match '^"AZ-TSTAPP' >> $outputFile

事实证明,上面的正则表达式不够具体;根据您的 comments ,这是您想出的适用于您的正则表达式:

@($scriptResult | Out-String -Stream) -match '^".*AZ-.*",".*",".*",".*"$' >> $outputFile

Json相关问答推荐

使用JSONata将具有相同键的字典合并

Jolt转换问题—使用键查找匹配对象

如何在JQ过滤器文件中使用多行?

组合不同属性的Jolt Spec

(Kotlin)com.google.gson.internal.LinkedTreeMap无法转换为com.example.phonetest2.model.HallData

迭代powershell双维json对象

使用 jq 工具将文本从 txt 文件转换为 json

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

Vue 3如何将参数作为json发送到axios get

在 postgresql 中将行转换为 json 对象

为什么JsonConvert反序列化对象以int但不长失败

C# 合并 2 个几乎相同的 JSON 对象

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

按 JSON 数据类型 postgres 排序

我应该如何处理 JSON 中的 HATEOAS 链接和引用?

使用 JSON.Net 的 C# 到 JSON 序列化

在 Java 中比较两个 JSON 文件的最佳方法

春天:返回@ResponseBodyResponseEntity>

从调试器获取 IntelliJ Idea 中的 JSON 对象

JSON - 是否有任何 XML CDATA 类似功能?