Powershell:在目录的最新文件中提取2个字符串之间的数据

我的powershell脚本应该执行以下操作:

  • 从目录中的最新日志文件读取数据
  • 在我的桌面上的输出文件中仅输出相关数据。

此刻,每当文档中出现“ lobbyid”一词时,我都会得到整行内容。

我的代码:

Get-ChildItem -Path  "C:\Program Files\Example\logs" |Sort-Object LastAccessTime -Descending | Select-Object -First 1 | Select-String –Pattern "lobbyid"| Select Filename,Line | Format-Table -wrap | Out-File $env:USERPROFILE\Desktop\output.txt -append'

在包含以下内容的日志文件中

XXXXXXXXXXXXXXXXXXXXX
{"seqid":5,"lobbyid":"9A74E75D-2BCB-4750-BF3A-87BB4992DC2D","mm":{"status":7}
{"seqid":12,"lobbyid":"CFDAAA9C-F973-40CF-A477-143A5810061D","mm":{"status":10}
YYYYYYYYYYYYYYYYYYYYY

我懂了

{"seqid":5,"lobbyid":"9A74E75D-2BCB-4750-BF3A-87BB4992DC2D","mm":{"status":7}
{"seqid":12,"lobbyid":"CFDAAA9C-F973-40CF-A477-143A5810061D","mm":{"status":10}

但是我想要输出

    Line 1: 9A74E75D-2BCB-4750-BF3A-87BB4992DC2D
    Line 2: CFDAAA9C-F973-40CF-A477-143A5810061D

或类似的东西。我尝试将'lobbyid'替换为'lobbyid(。*?)mm' 但这给出了相同的输出。

评论
  • Viola
    Viola 回复

    It looks like your log file lines contain JSON text, so you can try the following (which doesn't include a line number, which, as you've stated in a follow-up comment, isn't important; also, the Out-File call is omitted for brevity):

    Get-ChildItem 'C:\Program Files\Example\logs' |
      Sort-Object LastAccessTime -Descending |
        Select-Object -First 1 | 
          Select-String –Pattern lobbyid |
            ForEach-Object { ($_.Line | ConvertFrom-Json).lobbyid }
    

    Your example log lines are missing a closing } to be valid JSON, so if that is indeed the case in your real data, use $_.Line + '}' instead.