Need to add leading "0" to each octet of IP address

Welcome Forums General PowerShell Q&A Need to add leading "0" to each octet of IP address

Viewing 0 reply threads
  • Author
    Posts
    • #5860
      Participant
      Topics: 1562
      Replies: 0
      Points: 1
      Rank: Member

      by colt.45 at 2013-04-29 08:29:16

      I have some code that I have put together but I need to convert each octet to have 3 numbers. If for example I get the IP address of 10.100.33.52 I need to convert it to 010.100.033.052. Here is the code that I have:

      Foreach ($UpIp in $Results)
      {

      $Sqlserver = 'popsql2k8'
      $Sqlcatalog = 'netops'
      $SqlQuery = "SELECT host from dbo.View_DNSxDHCP WHERE dns_ip_alias = '$ModIp'"
      $Dataset = New-Object System.Data.Dataset
      $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
      $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
      $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
      $SqlCmd.CommandText = $SqlQuery
      $SqlCmd.Connection = $SqlConnection
      $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
      $SqlAdapter.SelectCommand = $SqlCmd
      $SqlAdapter.Fill($Dataset)
      $Dataset.Tables[0]
      $SqlConnection.Close()
      [string]$Comp = @($Dataset.Tables[0])[0].host
      invoke-command -computername $Comp -filepath c:\Temp\Wol1.ps1
      }

      $UpIp is a collection of IP’s in a specific subnet and I need to convert them to the format I talked about above to get the $ModIp variable so that I can match them to my DNS table. Thanks!

      by ArtB0514 at 2013-04-29 08:37:44

      I’m assuming that $ModIP is the modified IP address that you’re looking for.

      $ModIP = ($UpIP.Split('.') | foreach {"0:000}" -f [int]$_}) -join '.'

      by colt.45 at 2013-04-29 09:42:20

      Yes…$ModIp is the modified IP address that I need. With that line of code I get the following errors:

      Error formatting a string: Input string was not in a correct format..
      At C:\Users\archec\Desktop\AWSA\AWSA.ps1:809 char:51
      + $ModIP = ($UpIP.Split(‘.’) | foreach {"0:000}" -f [int]$_})
      -join ‘. …
      + ~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (0:000}:String) [], RuntimeExc
      eption
      + FullyQualifiedErrorId : FormatError

      Error formatting a string: Input string was not in a correct format..
      At C:\Users\archec\Desktop\AWSA\AWSA.ps1:809 char:51
      + $ModIP = ($UpIP.Split(‘.’) | foreach {"0:000}" -f [int]$_})
      -join ‘. …
      + ~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (0:000}:String) [], RuntimeExc
      eption
      + FullyQualifiedErrorId : FormatError

      Error formatting a string: Input string was not in a correct format..
      At C:\Users\archec\Desktop\AWSA\AWSA.ps1:809 char:51
      + $ModIP = ($UpIP.Split(‘.’) | foreach {"0:000}" -f [int]$_})
      -join ‘. …
      + ~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (0:000}:String) [], RuntimeExc
      eption
      + FullyQualifiedErrorId : FormatError

      Error formatting a string: Input string was not in a correct format..
      At C:\Users\archec\Desktop\AWSA\AWSA.ps1:809 char:51
      + $ModIP = ($UpIP.Split(‘.’) | foreach {"0:000}" -f [int]$_})
      -join ‘. …
      + ~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (0:000}:String) [], RuntimeExc
      eption
      + FullyQualifiedErrorId : FormatError

      Thanks for your help!

      by ArtB0514 at 2013-04-29 10:27:39

      Where did you put it? It needs to go inside the foreach clause before the sql query definition. Also, verify that $UpIP is just an IP address and not a more complex object. Try looking at $Results[0] to verify.

      Foreach ($UpIp in $Results)
      {
      $ModIP = ($UpIP.Split('.') | foreach {"0:000}" -f [int]$_}) -join '.'
      $Sqlserver = 'popsql2k8'
      $Sqlcatalog = 'netops'
      $SqlQuery = "SELECT host from dbo.View_DNSxDHCP WHERE dns_ip_alias = '$ModIp'"

      by colt.45 at 2013-04-29 10:33:51

      Here is the entire code snipet for the button in the form:
      $btnWol_Click={
      Get-ComputerName
      $SBPStatus.Text = "Retrieving MAC Address"
      $Sqlserver = 'popsql2k8'
      $Sqlcatalog = 'netops'
      $SqlQuery = "SELECT dhcp_client_mac_addr, dns_ip_alias from dbo.View_DNSxDHCP WHERE host = '$ComputerName'"
      $Dataset = New-Object System.Data.Dataset
      $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
      $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
      $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
      $SqlCmd.CommandText = $SqlQuery
      $SqlCmd.Connection = $SqlConnection
      $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
      $SqlAdapter.SelectCommand = $SqlCmd
      $SqlAdapter.Fill($Dataset)
      $Dataset.Tables[0]
      $SqlConnection.Close()
      #[string]$Ip = @($Dataset.Tables[0])[0].dns_ip_alias
      [string]$mac = @($Dataset.Tables[0])[0].dhcp_client_mac_addr
      [string]$Delimiter = ':'

      $rawAddress = $mac -replace '\W'

      switch ($Delimiter) {
      {$_ -match ':|-'} {
      for ($i = 2 ; $i -le 14 ; $i += 3) {
      $mac = $rawAddress = $rawAddress.Insert($i, $_)
      }
      break
      }

      '.' {
      for ($i = 4 ; $i -le 9 ; $i += 5) {
      $mac = $rawAddress = $rawAddress.Insert($i, $_)
      }
      break
      }

      default {
      $mac = $rawAddress
      }
      } # switch

      Clear
      [email protected]($mac.split(":") | foreach {$_.insert(0,"0x")})
      $MacAddress = [byte[]]($string[0], $string[1], $string[2], $string[3], $string[4], $string[5])
      $UDPclient = New-Object System.Net.Sockets.UdpClient
      $UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
      $packet = [byte[]](,0xFF * 102)
      6..101 | foreach {$packet[$_] = $MacAddress[($_%6)]}
      $UDPclient.Send($packet, $packet.Length)
      Start-Sleep -Seconds 5

      $ip = [System.Net.Dns]::GetHostAddresses($ComputerName) | Where-Object AddressFamily -EQ "InterNetwork" | Select-Object $_.IPAddressToString
      $ip0 = ([ipaddress] "$Ip").GetAddressBytes()[0]
      $ip1 = ([ipaddress] "$Ip").GetaddressBytes()[1]
      $ip2 = ([ipaddress] "$Ip").GetaddressBytes()[2]
      $Fip = "$ip0" + "." + "$ip1" + "." + "$ip2"

      $object = New-Object System.Object
      $object | Add-Member -type NoteProperty -Name Ip -Value $Ip
      $object | Add-Member -type NoteProperty -Name Mac -Value $mac
      $object | Export-Csv "c:\Temp\wol.csv"

      $Results = @()
      $count = 0
      $range = 15..200

      Foreach ($num in $range)
      {
      $ExeIp = "$fip.$num"
      If(Test-Connection "$ExeIP" -Quiet -Count 1)
      {
      $count = $count + 1
      $Results = $Results + $ExeIp
      }
      If ($count -eq 10)
      {Break}
      }

      Foreach ($UpIp in $Results)
      {
      $ModIP = ($UpIP.Split('.') | foreach {"0:000}" -f [int]$_}) -join '.'
      $Sqlserver = 'popsql2k8'
      $Sqlcatalog = 'netops'
      $SqlQuery = "SELECT host from dbo.View_DNSxDHCP WHERE dns_ip_alias = '$ModIp'"
      $Dataset = New-Object System.Data.Dataset
      $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
      $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
      $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
      $SqlCmd.CommandText = $SqlQuery
      $SqlCmd.Connection = $SqlConnection
      $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
      $SqlAdapter.SelectCommand = $SqlCmd
      $SqlAdapter.Fill($Dataset)
      $Dataset.Tables[0]
      $SqlConnection.Close()
      [string]$Comp = @($Dataset.Tables[0])[0].host
      invoke-command -computername $Comp -filepath c:\Temp\Wol1.ps1
      }

      $SBPStatus.Text = "WOL magic packet of length $($packet.Length) sent to $ComputerName"

      Start-Sleep -Seconds 10

      }

      $Relults is an array of strings which are the IP addresses.

      by ArtB0514 at 2013-04-29 10:39:54

      Boo on me! A typo when copying it across from my test. Sorry about that. This is correct:

      $ModIP = ($UpIP.Split('.') | foreach {"{0:000}" -f [int]$_}) -join '.'

      by colt.45 at 2013-04-29 10:49:05

      Thanks for all of your help! That does the trick. I don’t know why I was missing that…or why my brain had a meltdown when trying to convert the addresses. Thanks again!

Viewing 0 reply threads
  • The topic ‘Need to add leading "0" to each octet of IP address’ is closed to new replies.