How do I strip out everything but numbers in a variable?

I am trying to automate the setting of an IP address through PowerShell and I need to figure out what my interface number is.

I have developed the following:

$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 is when I try to grab just a number using:

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

      

it still leaves "InterfaceIndex" and underscores. This throws the next part of my script error because I just need a number.

Any suggestions?

+3


source to share


3 answers


This will do your job:

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

      



You don't actually need to double-select a property: do it like this:

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

      

+3


source


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

      

There is no point in choosing the default properties. If you want to save the object, follow these steps:

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

      



where f = first, ov = outvariable

$variablename.Interfaceindex

      

You don't need to Out-String

, as the cast to string is implicit on display. and if you try to work with that data further, PowerShell is smart enough to cast it from int to string and vice versa when needed.

+2


source


Answering your question, you can remove everything that is not a number from a variable by removing everything that is not a number (or rather a digit):

$x = $x -replace '\D'

      

However, your best bet would be to simply not add what you want to remove in the first place:

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

      

PowerShell cmdlets usually produce objects as output, so instead of treating those objects in inline form and stripping out the extra stuff, you usually just expand the value of the object you're interested in.

+2


source







All Articles