How to Get only numeric value in text file using powershell?

I have a text file sample.txt containing

computer
computer.pc = 1
pc

i want only number 1, where i want to assign that value to a variable

$number = Get -content "sample.txt"

>Solution :

You can extract the number by using the Regex Match method.

Example code to do this:

$number = ([regex]::Match((Get-content "sample.txt"), "\d+")).Value

The pattern \d+ means to match one or more decimal digits and using the Match method will return the first match found.

See Quantifiers in Regular Expressions for additional information regarding the quantifiers available.

Leave a Reply