j.r19
j.r19

Reputation: 55

How to strip out everything but numbers in a variable?

I'm trying to automate setting an IP address through PowerShell and I need to find out what my interfaceindex number is.

What I have worked out is this:

$x = ( Get-NetAdapter |
       Select-Object -Property InterfceName,InterfaceIndex |
       Select-Object -First 1 |
       Select-Object -Property Interfaceindex ) | Out-String

This will output:

InterfaceIndex
--------------
             3

Now the problem, when I try to grab only the number using:

$x.Trim.( '[^0-9]' )

it still leave the "InterfaceIndex" and the underscores. This causes the next part of my script to error because I just need the number.

Any suggestions?

Upvotes: 3

Views: 1083

Answers (3)

Ranadip Dutta
Ranadip Dutta

Reputation: 9123

This will get your job done:

( Get-NetAdapter | Select-Object -Property InterfceName,InterfaceIndex | Select-Object -First 1 | Select-Object -Property Interfaceindex).Interfaceindex

Actually you do not need two times to select the property: do like this:

( Get-NetAdapter |Select-Object -First 1| Select-Object -Property InterfceName,InterfaceIndex).Interfaceindex

Upvotes: 3

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Answering your immediate question: you can remove everything that isn't a number from a variable by, well, removing everything that isn't a number (or rather digit):

$x = $x -replace '\D'

However, a better aproach would be to simply not add what you want removed in the first place:

$x = Get-NetAdapter | Select-Object -First 1 -Expand InterfaceIndex

PowerShell cmdlets usually produce objects as output, so instead of mangling these objects into string form and cutting away excess material you normally just expand the value of the particular property you're interested in.

Upvotes: 3

4c74356b41
4c74356b41

Reputation: 72151

(Get-NetAdapter | select -f 1).Interfaceindex

No point in selecting properties as they are there by default. If you want to keep object do:

(Get-NetAdapter | select -f 1 -ov 'variablename').Interfaceindex

where f = first, ov = outvariable

$variablename.Interfaceindex

You don't need Out-String as cast to string is implicit when you output to screen. and if you try to work with this data further down powershell is clever enough to cast it from int to string and vice versa when needed.

Upvotes: 2

Related Questions