0

I am new to Powershell script I am using vmstat command and i am trying to filter values based on total memory and used memory.

I have done this way but i am not able to just filter value.

PS /home/ec2-user> $usedmem = vmstat -s | Select-String 'used memory'

PS /home/ec2-user> $usedmem

   217976 K used memory

But my question is,

how can i just get the value(217976) for used memory

I really appreciate your help

3 Answers 3

1

An approach using Regex pattern capture:

$usedMemLine = vmstat -s | Select-String "(.+) . used memory"
$usedValue = $usedMemLine.Matches[0].Groups[1].Value
Sign up to request clarification or add additional context in comments.

Comments

1

Here's one way. Split it on whitespace, and pick the first resulting array element.

(-split $usedmem)[0]

217976

1 Comment

I tried this way, It is working as well $usedstring = $usedmem.ToString().split()| where {$_} | select-object -first 1 PS /home/ec2-user> $usedstring 220980
0

A better RegEx approach:

if($usedMem -match "^\s*(\d+).*"){$matches[1]}

Explanation:

^ Match characters at the beggining of string
\s Match a White space
* Match 0 or more instances of previous character
( Start grouping of specific match
\d Match a 0-9 digit
+ Match 1 or more instances of previous character
) End grouping of specific match
. Match any character
* Match 0 or more instances of previous character

$matches[1] returns the K value only, where $matches[0] will return the whole string.

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.