2016-09-22 53 views
0

我试图使用一个power 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。 我用这个链接给我写剧本 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 

当我运行此脚本运行,但不会给予任何回应。似乎以某种方式选择字符串的输出不会加载到变量$newvolumeid

任何想法如何解决这个问题?或者我错过了什么?

PS:上面提到的帖子是3岁左右,不工作,因此我正在转贴。

+1

是'json'文件?如果是这样[检查这个帖子](http://stackoverflow.com/questions/16575419/powershell-retrieve-json-object-by-field-value) – gwillie

回答

0

您正在尝试读取JSON对象的属性。相反,使用正则表达式,你可以解析JSON和使用选择属性:

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

Awsome,这个工程。我能够整齐地获取信息。 – Abhijit

0

试试这个

$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 
+0

尽管您的解决方案可能有效,但它非常容易出错,不推荐使用。 –

相关问题