0

I am trying to use a power shell script to read the contents of a file and pick a specific type of word from it. I need to load the word that is found as a variable which I intend to use further downstream.

This is how my input file looks like:

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

The specific word I would like to pick is vol-xxxxxxxx. I used this link to write my script How to pass a variable in the select-string of powershell

This is how I am doing it:


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

When I run this script it runs but does not give any response. Seems somehow the output of select string is not loaded into the variable $newvolumeid.

Any idea how to resolve this? Or what I am missing?

PS: The post mentioned above is about 3 years old and doesn't work hence I am reposting.

Community
  • 1
  • 1
Abhijit
  • 73
  • 1
  • 5
  • 1
    is the file in `json`? if so [check this post out](http://stackoverflow.com/questions/16575419/powershell-retrieve-json-object-by-field-value) – gwillie Sep 22 '16 at 04:08

2 Answers2

0

You are trying to read a property of a JSON object. Instead of using regex, you can parse the JSON and select the property using:

Get-Content 'c:\reports\volume.jason' | ConvertFrom-Json | select -ExpandProperty VolumeId
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
0

Try this

$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 
BaronW
  • 151
  • 5