Help with a Powershell command

I have a script (not written by me) that is used to grab the local Computer’s IP address store it in a variable then insert it into a config file, the new batch of computers came in with multiple NIC’s and the scrip is failing to grab the correct address I would like to modify the script to one of the following.

  1. Only grab the variable if it is -like 192.168.X.X
  2. Only grab the Ip from the active connect Network connection

#Script to capture local IP Address and insert into config file

(old way) $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPV4Address

$ipV4 = Test-Connection -ComputerName (hostname) Get-Process | Where-Object IPV4Address -Match “172.21..” | Select -ExpandProperty IPV4Address

$content = Get-Content -Path ‘C:\Program Files (x86)\sysprep\Admin.config’

$newContent = $content -replace ‘fixme’,$ipV4.IPAddressToString

$newContent |Set-Content -Path 'C:\Program Files (x86)\sysprep\Admin.config’Preformatted text

Hi and welcome. First things first, you gotta format your code for readability. There’s a “preformatted text” button in the post/editor box that will help you with this.
It should look like this:

#Script to capture local IP Address and insert into config file
#$ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPV4Address
$ipV4 = Test-Connection -ComputerName (hostname) Get-Process | Where-Object IPV4Address -Match "172.21.." | Select -ExpandProperty IPV4Address
$content = Get-Content -Path "C:\Program Files (x86)\sysprep\Admin.config"
$newContent = $content -replace "fixme",$ipV4.IPAddressToString
$newContent | Set-Content -Path "C:\Program Files (x86)\sysprep\Admin.config"

Now you’re method seems to be the PS equivalent of pinging the computer, from the computer, to derive the IP address.
Take a look at the Get-NetAdapter and Get-NetIPAddress.

2 Likes

Thank you. What I am trying to do it grab the IP address of the compute, store it in a variable then paste it into a Config file, this simple process worked but the last batch of computers we received came with Multiple NIC’s so it doesn’t know which one to grab anymore so I need to limit the scope some how. I am not a PS person I can normally wiggle my way around but I can’t see to find syntax that will grab just the local address and place it into the variable. Note the script will still work if I disable all the other NIC’s on the system

If there is only one IP, you can easily find it and which NIC has it with the commands @grey0ut pointed to. If there are multiple IPs, how will the script discern which is the correct one?

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.