2016-09-22 54 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

儘管您的解決方案可能有效,但它非常容易出錯,不推薦使用。 –

相關問題