Select 来自文本文件的特定类型的单词并将其加载到变量中

Select a particular type of word from a text file and load it in a Variable

我正在尝试使用强大的 shell 脚本来读取文件的内容并从中选择特定类型的单词。我需要加载找到的单词作为我打算在下游进一步使用的变量。

这是我的输入文件的样子:

{
    "AvailabilityZone": "ap-northeast-1b", 
    "VolumeType": "gp2", 
    "VolumeId": "vol-087238f9", 
    "State": "creating", 
    "Iops": 100, 
    "SnapshotId": "", 
    "CreateTime": "2016-09-15T12:17:27.952Z", 
    "Size": 10
}

我想选择的具体词是vol-xxxxxxxx。 我用这个 link 来写我的脚本 How to pass a variable in the select-string of powershell

我是这样做的:


$Filename = "c:\reports\volume.jason"
$regex = "^[vol-][a-z0-9]{8}$"
$newvolumeid=select-string -Pattern $regex -Path $filename > C:\Reports\newVolumeid.txt
$newVolumeid

当我 运行 这个脚本时它 运行s 但没有给出任何响应。似乎以某种方式 select 字符串的输出未加载到变量 $newvolumeid 中。

知道如何解决这个问题吗?或者我缺少什么?

PS:上面提到的 post 已经有大约 3 年的历史了,无法正常工作,因此我正在重新 posting。

您正在尝试读取 JSON 对象的 属性。除了使用正则表达式,您还可以使用以下方法解析 JSON 和 select 以及 属性:

Get-Content 'c:\reports\volume.jason' | ConvertFrom-Json | select -ExpandProperty VolumeId

试试这个

$Inpath = "E:\tests\test.txt"

$INFile = Get-Content $Inpath 

$NeedsTrimming = $INFile.Split(" ") | ForEach-Object {if ($_ -like '*vol-*'){$_}}

$FirstQuote = $NeedsTrimming.IndexOf('"')
$LastQuote = $NeedsTrimming.LastIndexOf('"')

$vol = $NeedsTrimming.Substring(($FirstQuote + 1),($LastQuote - 1))

$vol