基于选择字符串的Powershell筛选器值

基于选择字符串的Powershell筛选器值,powershell,Powershell,我不熟悉Powershell脚本 我使用vmstat命令,并尝试根据总内存和已用内存筛选值 我已经这样做了,但我不能只过滤值 PS/home/ec2 user>$usedmem=vmstat-s |选择字符串“已用内存” PS/home/ec2用户>$usedmem 217976 K used memory 但我的问题是 我怎样才能得到已用内存的值(217976) 我真的很感谢你的帮助这里有一个方法。它在空格上单击,并拾取第一个生成的数组元素 (-split $usedmem)[0]

我不熟悉Powershell脚本 我使用vmstat命令,并尝试根据总内存和已用内存筛选值

我已经这样做了,但我不能只过滤值

PS/home/ec2 user>$usedmem=vmstat-s |选择字符串“已用内存”

PS/home/ec2用户>$usedmem

   217976 K used memory
但我的问题是

我怎样才能得到已用内存的值(217976)

我真的很感谢你的帮助

这里有一个方法。它在空格上单击,并拾取第一个生成的数组元素

(-split $usedmem)[0]

217976
这里有一条路。它在空格上单击,并拾取第一个生成的数组元素

(-split $usedmem)[0]

217976
采用以下方法:

采用以下方法:


更好的正则表达式方法:

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

^ 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]
仅返回K值,其中
$matches[0]
将返回整个字符串。

更好的正则表达式方法:

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

^ 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]
仅返回K值,其中
$matches[0]
将返回整个字符串。

我尝试过这种方法,它也能正常工作$usedstring=$usedmem.ToString().split();其中{$}选择对象-第一个1ps/home/ec2用户>$usedstring 220980我尝试过这种方法,它也能正常工作$usedstring=$usedtem.ToString().split()|其中{$}|选择对象-前1个PS/home/ec2用户>$usedstring 220980