0

Have a text file with so many contents like this:

AllocatedStorage           : 5
InstanceName               : snapshotinstance
SnapshotName               : Testsnapshot
SnapshotCreateTime         : 8/26/2015 8:34:47 AM

AllocatedStorage           : 5
InstanceName               : snapshotinstance
SnapshotName               : Backupsnapshot
SnapshotCreateTime         : 7/31/2015 8:00:00 AM

I need to read a specific string (which is read from another file) and if an exact match is found then I need to retrieve another string which is there within that block. For example, suppose if my search string is "7/31/2015 8:00:00 AM" then I need to retrieve SnapshotName for that specific block.

Is there a way to achieve this? Any help would be really appreciated.

2 Answers 2

1

Something like this maybe:

$File = Get-Content -Path 'S:\Test\File.txt'
$SearchTerm = '7/31/2015 8:00:00 AM'

$LineNr = $File | Select-String -Pattern $SearchTerm | Select-Object -ExpandProperty LineNumber
$File[$LineNr-2] | Split-String ':' | Select-Object -Last 1
Sign up to request clarification or add additional context in comments.

Comments

1

I was looking at your data and it looked like a good candidate for ConvertFrom-StringData. Lets use regex to split up your log file into is property groups and create PowerShell Objects from the data.

$snapshotData = (Get-Content -Raw "c:\temp\log.log")  -split '\s+(?=AllocatedStorage)' | ForEach-Object {
    # ConvertFrom-StringData needs name=value so we convert the colons.
    $Stringdata = $_-replace '\s+:','='
    New-Object PSObject -Property  $(ConvertFrom-StringData $Stringdata)
}

Using \s+: helps ensure we don't replace the colons inside the date strings. Now you can search the data and return what you are looking for.

$snapshotData | Where-Object{$_.SnapshotCreateTime -eq "7/31/2015 8:00:00 AM"} | Select-Object -ExpandProperty SnapshotName

Which would return: Backupsnapshot. Using custom objects can make it easier to get more complex data quickly.

Since we use -Raw you would need PowerShell 3.0 but could easily be replace with Out-String instead if need be.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.