Plazma
Plazma

Reputation: 147

PowerShell Auto assign IP

A computer is sent to a random location and gets a random IP address, but my task is set a correct IP address ended on .105, X.X.X.105.

My problem is to get the only IP address and edit it to the valid. Example Computer get 10.10.10.132 and I want to change it to 10.10.10.105 I don't know how to edit the IP address. I thinking about Split("."" ")

All computers are W10 and in a domain. I chose to make a script (as a scheduled task) that runs after turn on the computer and assign the IP address. Default Gateway is always X.X.X.254.

#check IP and get IP
$ipDefault = (Get-NetIPAddress -InterfaceAlias "Ethernet").IPAddress

#Here should be code to Get first 24 prefix length of network with the last dote

$IPComputer = "$ip + '105'"
$Gateway = "$ip + '254'"

#assigning an IP address
New-NetIPAddress –InterfaceAlias “Ethernet” –IPv4Address $IPComputer –PrefixLength 24 -DefaultGateway $Gateway
Set-DnsClientServerAddress -InterfaceAlias “Ethernet” -ServerAddresses 8.8.8.8, 8.8.4.4

I know I can put manually IP address, but I want to make the fully automatic script.

Upvotes: 0

Views: 482

Answers (1)

Ash
Ash

Reputation: 3246

You can use LastIndexOf and Substring. This will split the string by the last occurrence of '.'.

You also need to ensure that you are only returning IPv4 addresses.

$ipDefault = (Get-NetIPAddress -InterfaceAlias "Ethernet" -AddressFamily IPv4).IPAddress
$threeOctets = $ipDefault.Substring(0,$ipDefault.LastIndexOf('.'))
$newIP = $threeOctets + ".105"

Upvotes: 1

Related Questions