Cheries
Cheries

Reputation: 892

How to get a specific string in array using powershell?

I have a text file. The text file contain of this

Name(0x0)/Class(0x17,0x0)/Format(0x0,0xFFFF,0x0)

I want to get this string only Format(0x0,0xFFFF,0x0)

I try to split it and get the array number. BUT THE PROBLEM is this format text file sometime change. This string Format(0x0,0xFFFF,0x0) NOT always in the last array, and the total of array sometime different as well. like this.

Name(0x0)/Class(0x17,0x0)/Class2(0000,0000)/Format(0x0,0xFFFF,0x0)
or
Name(0x0)/Class(0x17,0x0)/Format(0x0,0xFFFF,0x0)/Class2(0000,0000)

My expectation, I can get this string Format(0x0,0xFFFF,0x0) , wherever it's place. Anyone can help me please. Thanks a lot.

$File = Get-Content .\PC.txt
$split = $File -split "/"
$found= $split[2]
$found

Upvotes: 1

Views: 672

Answers (2)

Cheries
Cheries

Reputation: 892

I found this simple way as well

$File = Get-Content .\PC.txt
$split = $File -split "/"
$found = $split -like "*Format*"

it works for me.

Upvotes: 0

mklement0
mklement0

Reputation: 437823

As iRon suggests, you can use Select-String with a regular expression as follows:

(Select-String 'Format\(.+?\)' .\PC.txt).Matches.Value

The .Matches.Value part extracts what the regular expression Format\(.+?\) matched from each selected line in file .\PC.txt, via the [Microsoft.PowerShell.Commands.MatchInfo] instances that Select-Object outputs.

A simpler solution will be possible once the -OnlyMatching switch gets implemented, which directly outputs only the matching parts of selected lines.

# Upcoming feature, not yet implemented as of PowerShell Core 7.0.0-preview.5
Select-String 'Format\(.+?\)' .\PC.txt -OnlyMatching

Upvotes: 1

Related Questions