VMware Cloud Community
drivera01
Enthusiast
Enthusiast
Jump to solution

powershell variables setting

Hi,

What would be the easist way to acheive this:

I have an IP, 123.45.56.79

$myip = "123.45.56.79"

I need to capture the  subnet: 56 and place it in this string

network-056  (notice the 0 )

$mynetwork = "network-056"

Thank you for the help,

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

That should be no problem.

With the D3 format we specify that the output should take 3 positions and if needed be filled up with leading zeroes.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
4 Replies
LucD
Leadership
Leadership
Jump to solution

You could do something like this

$t = "123.45.56.79"
$mynetwork = "network-{0:D3}" -f [int]($t.Split('.')[2])

With the Split function the string is seperated in 4 parts.

We take the 3rd part (index 2).

With the format operator we format that number in the correct format.

The D format allows us to specify leading zeros, but it requires an integer as input, hence the [int] cast on the right operand.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
drivera01
Enthusiast
Enthusiast
Jump to solution

Hi, LucD

What would happen if the integer I need to put on its place is legs say 155

Without a 0 in the beginning.

So it could I have to pick networks

056

070

086

145

155

..

..

Etc

Thanks

0 Kudos
LucD
Leadership
Leadership
Jump to solution

That should be no problem.

With the D3 format we specify that the output should take 3 positions and if needed be filled up with leading zeroes.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
drivera01
Enthusiast
Enthusiast
Jump to solution

Thank you... perfect!!

0 Kudos