SoFunction
Updated on 2025-03-09

PowerShell scripts implement the method of automatically obtaining IP addresses and setting static IP addresses in network card DHCP

PowerShell sets DHCP to automatically obtain the IP address. PowerShell can easily set the local computer to enable DHCP to dynamically obtain the IP address, which requires WMI extension. This article introduces detailed scripting programs.

PowerShell sets DHCP to automatically obtain IP address

PowerShell can easily set up DHCP to enable local computers to dynamically obtain IP addresses, which requires WMI extensions. This article introduces detailed scripting programs.

The first step is to use Get-WmiObject to obtain the specified network card configuration object

Copy the codeThe code is as follows:
$netAdp = gwmi win32_networkadapterconfiguration | ?{$_.index -eq 7}

illustrate:
1. gwmi is the alias of the cmdlet Get-WmiObject. For convenience, use gwmi directly.
2. win32_networkadapter configuration is an object for network card configuration in WMI. After obtaining it, you can operate the network card configuration.
3. ?{$_.index -eq 7} From all the obtained network card objects, filter network cards with serial number 7. Brother Hong wants to remind everyone to pay attention to this place. You can do not circulate the following conditions first. The program will output all network card information, and then you select the index value of the network card information you need to modify.
4. For each network card configuration object, the contents contained are as follows.

Copy the codeThe code is as follows:

DHCPEnabled      : True
IPAddress        :
DefaultIPGateway :
DNSDomain        :
ServiceName      : k57nd60a
Description      : Broadcom NetLink (TM) Gigabit Ethernet
Index            : 7

Step 2: Check the current DHCP configuration of the selected network card

Copy the codeThe code is as follows:

PS C:\Users\zhanghong> $
True

An output value of True means that DHCP is currently enabled. Of course, if the output will be False, it means that DHCP is not enabled, and it will be configured with a static IP.

Step 3: Turn on and finish DHCP to automatically obtain IP

Open command:

Copy the codeThe code is as follows:

$()

To turn off DHCP, you must configure a static IP address:
Copy the codeThe code is as follows:

$("192.168.0.2", "255.255.255.0")

OK, this is what I will introduce when using PowerShell to configure DHCP or static IP addresses. I hope it will be helpful to everyone.