Powershell .ToString()

By | April 22, 2024

I’m posting this as I spent too much time on figuring out how to convert the current IP of a machine and turn the IP address into an array. I needed this so I can change the last octet to a couple of other values that I would set later in the script. Powershell has an odd way of outputting data into different types such as objects. Objects can be frustrating when you just want a string output, but objects do give you all types of other possible information from the data you are querying.

The output of my variable $ipv4 is an object.

I mean there is quite a bit of data to choose from, but I just wanted the IP address. So, after digging around, I realized I needed to pass a PSObject .ToString() to my variable which will return the string representation for this object.

Finally! My variable only outputting the string value.

Now that I can get the actual string value I need, I can then use split(‘.’) to split the string at each period character to an array. For some reason, getting just the string value on this one stumped me longer than it should have. So, here it is for anyone that ever needs this (Or myself for future reference). Splitting your IP address into an array.

$ipV4 = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address
$ipArray =  ($ipV4.ToString()).Split(".")

Write-Host("IPV4 Output :" + $ipV4)
Write-Host("Octect1 [0] :" + $ipArray[0])
Write-Host("Octect2 [1] :" + $ipArray[1])
Write-Host("Octect3 [2] :" + $ipArray[2])
Write-Host("Octect4 [3] :" + $ipArray[3])