Dominic Brunetti
Dominic Brunetti

Reputation: 1069

Converting input to integer and doing arithmetic in powershell

not sure how to convert a string to an integer and then do an "add 1" to it. Here's what I'm trying to do:

1) Capture an IP address from a prompt

2) create list of variables with the increasing IPs as such:

$startIP = Read-Host 
$ip1 = $startIP
$ip2 = $ip1 + 1
$ip3 = $ip2 + 1

So for example, we'd input 10.0.0.1, and then $ip2 would be 10.0.0.2 and so on.

I know I need to convert this to an integer after reading the input, but am unsure how to do that. Many thanks!

Upvotes: 0

Views: 586

Answers (1)

Nkosi
Nkosi

Reputation: 247641

Found these functions that converts an IP to an Int64 and back

Function Convert-IpToInt64 () { 
    param ([String]$ip) 
    process { 
        $octets = $ip.split(".") 
        return [int64]([int64]$octets[0]*16777216 +[int64]$octets[1]*65536 +[int64]$octets[2]*256 +[int64]$octets[3]) 
    }
} 

Function Convert-Int64ToIp() { 
    param ([int64]$int) 
    process {
        return (([math]::truncate($int/16777216)).tostring()+"."+([math]::truncate(($int%16777216)/65536)).tostring()+"."+([math]::truncate(($int%65536)/256)).tostring()+"."+([math]::truncate($int%256)).tostring() )
    }
}

With that you can now convert the input to an something that can be incremented

$startIP = Read-Host 
$ip1 = Convert-IpToInt64 $startIP
$ip2 = $ip1 + 1
$ip3 = $ip2 + 1

Upvotes: 1

Related Questions