Chelseawillrecover
Chelseawillrecover

Reputation: 2644

Get value between two strings or characters with spaces in it

Hi I created a simple PowerShell script to analyze the fragmentation level of a volume for monitoring:

cd /
$c1 = defrag c: -a | findstr 'fragmented'
$c1.split('=')[1].trim()

The result I get is either 0% or 10% that is with single digit or double digits. What I would like is a regex command to get just the numeric value. I could still add another split command for % but was hoping a regex could do this without having multiple splits

Please note without the split command the original result looks like this with spaces at beginning and after the equals sign.

        Total fragmented space      = 0%

Upvotes: 1

Views: 237

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200383

Something like this should work:

$fragmentation = (defrag c: /a) -match '%$' -replace '.*= (\d)%$','$1'

The -match operation restricts the output to just the lines ending with a % and the -replace operation extracts the numeric value from those lines. Since the line stating the fragmentation level is the only line with a percent value, the result is the numeric value of the fragmentation.

I have to agree with @alroc, though: using WMI is a better solution to your problem.

Upvotes: 1

mjolinor
mjolinor

Reputation: 68311

A regex solution might look like this:

$text = '10%'
$text -replace '(\d{1,2})%','$1'

10

But honestly, that's over complicated for what's required. You can easily modify your existing script to also trim off the % like this:

$c1.split('=')[1].trim(' %')

Upvotes: 1

Aleks G
Aleks G

Reputation: 57326

Simply strip the last character from what you got:

SET pct=$c1.split('=')[1].trim()
echo %pct:~0,-1%

Upvotes: -1

Related Questions