четверг, 24 апреля 2014 г.

Включение DHCP через скрипт или групповую политику

Включение DHCP через скрипт или групповую политику

Оставлю здесь парочку скриптов, для включение DHCP клиента через групповую политику а также включения статического IP и конфигурирования DNS и Gateway. Скрипты взяты с нескольких ресурсов, может кому пригодятся.
Function Set-RvNetIpAddress 
{ 
    <# 
    .NOTES 
        Version: 1.0 
 
    .SYNOPSIS 
        Set static IP address or DHCP to multiple network interface controllers (NICs). It is possible to set default gateway and DNS servers and the configured network adapters do not have to be connected to the network. It is possible to input for example 192.168.1.1 or 192.168.1.1/24 or 192.168.1.1 and 255.255.255.0. 
 
    .DESCRIPTION 
        Developer 
            Developer: Rudolf Vesely, http://rudolfvesely.com/ 
            Copyright (c) Rudolf Vesely. All rights reserved 
            License: Free for private use only 
 
            RV are initials of the developer's name Rudolf Vesely and distingue names of Rudolf Vesely's cmdlets from the other cmdlets. Type “Get-Command *-Rv*” (without quotes) to list all Rudolf Vesely’s cmdlets (functions). 
 
        Description 
            Set static IP address or DHCP on multiple NICs. It is possible to set default gateway and DNS servers and the configured network adapters do not have to be connected to the network. 
 
            Microsoft did a great job with the new cmdlets in PowerShell 3.0 but it is not possible to set the static IP address with these cmdlets when the NIC is not connected to network so it is not possible to pre-configure server before connection into network. 
 
        Advices 
            Use -Verbose switch. All Rudolf Vesely's cmdlets (functions) are verbose with a lot of details. 
 
        Requirements 
            Developed and tested on PowerShell 4.0 but should be functional on PowerShell 3.0. 
            To use this function another function is required. Search for another contributions from the Rudolf Vesely (developer). 
 
        Installation 
            Put text ". C:\Path\Where\The\PS1\File\Is\Saved\this_file.ps1" (without quotes) into one of the PowerShell profile files (for example in the Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1). 
 
    .PARAMETER IpAddress 
        IPv4 address without defined subnet mask (for example 192.168.1.2) or with CIDR notation (for example 10.25.85.62/16) - leading zeros are allowed (for example 010.001.100.007) 
 
    .PARAMETER SubnetMaskCidr 
        Subnet mask in CIDR notation (Prefix Length) - for example 16 (stands for 255.255.0.0) 
 
    .PARAMETER SubnetMask 
        Subnet mask - leading zeros (for example 255.255.000.000) are allowed. 
 
    .PARAMETER DefaultGateway 
        Default gateway - leading zeros are allowed (for example 192.168.002.001) 
 
    .PARAMETER DnsServer 
        IP address of the preferred DNS server and optionally IPs of alternate DNS servers. 
 
    .PARAMETER InputObject 
        Specifies the input to this cmdlet. You can use this parameter, or you can pipe the input to this cmdlet. 
 
    .PARAMETER InterfaceIndex 
        Index of the NIC (for example 8) 
 
    .PARAMETER InterfaceAlias 
        Designation of the NIC (for example "Ethernet 2") 
 
    .PARAMETER Type 
        Type of the IP configuration that should be set. Possibilities: DHCP, Static 
 
    .PARAMETER RemoveExistingDefaultGateway 
        Remove existing default gateway if the value is not passed as the argument of the parameter (if specified, it is always automatically overwritten). 
 
    .PARAMETER RemoveExistingDnsServer 
        Remove existing DNS server if the value is not passed as the argument of the parameter (if specified, it is always automatically overwritten). 
 
    .PARAMETER Force 
        Prompts for confirmation before running the cmdlet are disabled (same as -Confirm:$false). 
 
    .EXAMPLE 
        Get-NetIPInterface -InterfaceAlias 'My Secret LAN no. *' | Set-RvNetIpAddress -Type DHCP -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -Type DHCP -InterfaceAlias 'Connection to Matrix', 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -Type DHCP -InterfaceIndex 14, 15 -DnsServer '10.12.58.003', '10.12.58.004' -Confirm -Verbose 
 
    .EXAMPLE 
        Get-NetIPInterface -InterfaceAlias 'My Secret LAN no. *' | Set-RvNetIpAddress -DnsServer '192.168.55.10', '192.168.55.11' -Type DHCP -InterfaceAlias 'Connection to Matrix', 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -DnsServer '192.168.55.10', '192.168.55.11' -Type DHCP -InterfaceAlias 'Connection to Matrix', 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Get-NetIPInterface -InterfaceAlias 'My Secret LAN no. 1' | Set-RvNetIpAddress -IpAddress '192.168.77.55/24' -Type Static -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -IpAddress '192.168.77.55/24' -Type Static -InterfaceAlias 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -IpAddress '192.168.77.56/24' -DefaultGateway '192.168.77.4' -DnsServer '192.168.77.99' -Type Static -InterfaceAlias 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -IpAddress '192.168.007.55/24' -DefaultGateway '192.168.7.003' -DnsServer '192.168.007.099', '192.168.7.100' -Type Static -InterfaceAlias 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddress -IpAddress '192.168.077.005' -SubnetMaskCidr 24 -Type Static -InterfaceAlias 'Management NET for Matrix' -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddressDhcp -InterfaceAlias 'Matrix 1', "Trinity's NET 2" -Verbose 
 
    .EXAMPLE 
        Set-RvNetIpAddressStatic -IpAddress '192.168.70.100' -SubnetMask '255.255.128.0' -InterfaceAlias 'Management NET for Matrix' -Verbose 
 
    .INPUTS 
        Microsoft.Management.Infrastructure.CimInstance[] 
 
    .OUTPUTS 
        Microsoft.Management.Infrastructure.CimInstance 
        Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetIPAddress 
 
    .LINK 
        http://rudolfvesely.com/ 
    #> 
 
    [CmdletBinding( 
        DefaultParametersetName = 'InputObject', 
        SupportsShouldProcess = $true, 
        ConfirmImpact = 'Medium' 
    )] 
 
    Param 
    ( 
        [Parameter( 
            Mandatory = $false, 
            Position = 0, 
            # ParameterSetName = $null, 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = '' 
        )] 
        [Alias('IpV4Address')] 
        [ValidateScript({ [string]::IsNullOrEmpty($_-or 
            $_ -match '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' + 
            '(/0*([1-9]|[12][0-9]|3[0-2]))?$' })] # Null or empty or <IPv4> or <IPv4>/<CIDR> 
        [string] 
        $IpAddress, 
 
        [Parameter( 
            Mandatory = $false, 
            Position = 1, 
            # ParameterSetName = $null, 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [Alias('PrefixLength')] 
        [ValidateRange(1,32)] 
        [ValidateScript({ !$_ -or 
            ($_ -ge 1 -and $_ -le 32) })] # Null or 0 or range 
        [int] 
        $SubnetMaskCidr, 
 
        [Parameter( 
            Mandatory = $false, 
            Position = 2, 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [ValidateScript({ [string]::IsNullOrEmpty($_-or 
            $_ -match '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' })] # Null or empty or IPv4 
        [string] 
        $SubnetMask, 
 
        [Parameter( 
            Mandatory = $false, 
            # Position = , 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [ValidateScript({ [string]::IsNullOrEmpty($_-or 
            $_ -match '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' })] # Null or empty or IPv4 
        [string] 
        $DefaultGateway, 
 
        [Parameter( 
            Mandatory = $false, 
            # Position = , 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [Alias('DnsResolver')] 
        [ValidateScript({ [string]::IsNullOrEmpty($_-or 
            $_ -match '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + 
            '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' })] # Null or empty or IPv4 
        [string[]] 
        $DnsServer, 
 
        [Parameter( 
            Mandatory = $true, 
            # Position = , 
            ParameterSetName = 'InputObject', 
            ValueFromPipeline = $true, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [Microsoft.Management.Infrastructure.CimInstance[]] 
        $InputObject, 
 
        [Parameter( 
            Mandatory = $true, 
            # Position = , 
            ParameterSetName = 'InterfaceIndex', 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [ValidateRange(1,65535)] 
        [ValidateScript({ [bool](Get-NetIPInterface -InterfaceIndex $_) })] 
        [int[]] 
        $InterfaceIndex, 
 
        [Parameter( 
            Mandatory = $true, 
            # Position = , 
            ParameterSetName = 'InterfaceAlias', 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [ValidateLength(1,255)] 
        [ValidateScript({ [bool](Get-NetIPInterface -InterfaceAlias $_) })] 
        [string[]] 
        $InterfaceAlias, 
 
        [Parameter( 
            Mandatory = $true, 
            # Position = , 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [ValidateSet( 
            'DHCP', 
            'Static' 
        )] 
        [string] 
        $Type, 
 
        [Parameter( 
            Mandatory = $false, 
            # Position = , 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [switch] 
        $RemoveExistingDefaultGateway = $true, 
 
        [Parameter( 
            Mandatory = $false, 
            # Position = , 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [switch] 
        $RemoveExistingDnsServer = $true, 
 
        [Parameter( 
            Mandatory = $false, 
            # Position = , 
            # ParameterSetName = , 
            ValueFromPipeline = $false, 
            ValueFromPipelineByPropertyName = $false, 
            ValueFromRemainingArguments = $false 
            # HelpMessage = 
        )] 
        [switch] 
        $Force = $false 
    ) 
 
    Begin 
    { 
        Write-Verbose '- Set-RvNetIpAddress: Start' 
        Write-Verbose '    - Copyright (c) Rudolf Vesely (http://rudolfvesely.com/). All rights reserved' 
        Write-Verbose '        - License: Free for private use only' 
 
        if (!(Get-Command -Name Get-RvNetIpAddressDetails -ErrorAction SilentlyContinue)) 
        { 
            Write-Error 'To run this function another function Get-RvNetIpAddressDetails from the Rudolf Vesely developer is required.' 
            throw 'Missing required function: Get-RvNetIpAddressDetails' 
        } 
 
 
 
        <# 
        Functions 
        #> 
 
        # Remove leading zeros - 127.000.100.001 -> 127.0.100.1 
        Function Remove-RvNetIpAddressLeadingZeros 
        { 
            <# 
            .DESCRIPTION 
                Developer 
                    Developer: Rudolf Vesely, http://rudolfvesely.com/ 
                    Copyright (c) Rudolf Vesely. All rights reserved 
                    License: Free for private use only 
            #> 
 
            Param 
            ( 
                [string[]] 
                $IpAddress 
            ) 
 
            foreach ($ipAddressItem in $IpAddress) 
            { 
                # Return 
                $ipAddressItem -replace '0*([0-9]+)''${1}' 
            } 
        } 
    } 
 
    Process 
    { 
        # Correction of the IP addresses 
        if ($DnsServer) { $dnsServerItems = Remove-RvNetIpAddressLeadingZeros -IpAddress $DnsServer } 
 
        # Obtaining NIC index 
        if ($InterfaceIndex) 
        { 
            $InterfaceIndexItems = $InterfaceIndex 
        } 
        elseif ($InputObject -or $InterfaceAlias) 
        { 
            Write-Verbose '' 
            Write-Verbose ('    - Obtaining indexes from the NICs:') 
 
            $InterfaceIndexItems = @() 
 
            foreach($interfaceItem in $InputObject) 
            { 
                Write-Verbose ('        - NIC alias: {0}' -$interfaceItem.ifAlias) 
 
                $InterfaceIndexItems +$interfaceItem.ifIndex 
 
                Write-Verbose ('            - Index: {0}' -f [string]$interfaceItem.ifIndex) 
            } 
 
            foreach($InterfaceAliasItem in $InterfaceAlias) 
            { 
                Write-Verbose ('        - NIC alias: {0}' -$InterfaceAliasItem) 
 
                $nic = Get-NetIPInterface -InterfaceAlias $InterfaceAliasItem 
                if ($nic.Count -gt 1) { throw 'There are multiple NICs with one or more of the defined aliases.' } 
 
                $InterfaceIndex = $nic.ifIndex 
                if (!$InterfaceIndex) { throw 'One or more defined interface does not exists.' } 
 
                $InterfaceIndexItems +$InterfaceIndex 
                Write-Verbose ('            - Index: {0}' -f [string]$InterfaceIndex) 
            } 
        } 
        else { throw 'Interface has to be defined by Object, Index or Alias.' } 
 
        # Setting IP addresses 
        :settingIpAddresses foreach($InterfaceIndexItem in $InterfaceIndexItems) 
        { 
            Write-Verbose '' 
            Write-Verbose ('    - Processing NIC with index: {0}' -f [string]$InterfaceIndexItem) 
 
            if ($Type -eq 'DHCP') 
            { 
                # Confirm 
                if ($Force -or $PSCmdlet.ShouldProcess('Computer: {0}' -$env:COMPUTERNAME, 'Set DHCP to NIC with index {0}.' -$InterfaceIndexItem)) 
                { 
                    Write-Verbose '        - Setting DHCP...' 
                    Write-Verbose '            - Details:' 
                    Write-Verbose ('                - DnsServer: {0}' -$(if ($dnsServerItems) { ($dnsServerItems -join ', ') } else { 'Not set' } )) 
                    Write-Verbose '            - Configurations:' 
 
                    try 
                    { 
                        Write-Verbose '                - DHCP' 
 
                        # Set-NetIPInterface -DHCP Enabled is not always working properly. 
                        $null = Invoke-Expression ('netsh interface ipv4 set address name=' + $InterfaceIndexItem + ' source=dhcp'-ErrorAction Stop 
 
                        Write-Verbose '                    - Results: Success' 
                    } 
                    catch 
                    { 
                        Write-Error 'It is not possible to set DHCP. The currently processed NIC will be skipped.' 
                        continue settingIpAddresses 
                    } 
 
                    if ($dnsServerItems) 
                    { 
                        try 
                        { 
                            Write-Verbose ('                - DNS server ({0}): {1}' -f [string]$dnsServerItems.Count, ($dnsServerItems -join ', ')) 
 
                            Set-DnsClientServerAddress -InterfaceIndex 15 -ServerAddresses ($dnsServerItems) 
 
                            Write-Verbose '                    - Results: Success' 
                        } 
                        catch 
                        { 
                            Write-Error 'Error during setting DNS server.' 
                            continue settingIpAddresses 
                        } 
                    } 
                    elseif ($RemoveExistingDnsServer) 
                    { 
                        try 
                        { 
                            Write-Verbose '                - Resetting DNS servers in order to remove any existing DNS servers that could be set on the defined NIC.' 
 
                            Set-DnsClientServerAddress -InterfaceIndex $InterfaceIndexItem -ResetServerAddresses -ErrorAction Stop 
 
                            Write-Verbose '                    - Results: Success' 
                        } 
                        catch 
                        { 
                            Write-Error 'It is not possible to reset DNS servers in order to remove existing DNS servers.' 
                            continue settingIpAddresses 
                        } 
                    } 
                } 
            } 
 
            else # if ($Type -eq 'Static') 
            { 
                # Confirm 
                if ($Force -or $PSCmdlet.ShouldProcess('Computer: {0}' -$env:COMPUTERNAME, 'Set static IP address to NIC with index {0}.' -$InterfaceIndexItem)) 
                { 
                    # Testing and correction of the IP addresses 
                    $parametersAndArguments = @{} 
                    if ($IpAddress) { $parametersAndArguments.Add('IpAddress'$IpAddress) } 
                    else 
                    { 
                        throw 'In order to set static IP address the IP address has to be provided.' 
                    } 
 
                    if ($SubnetMaskCidr) { $parametersAndArguments.Add('SubnetMaskCidr'$SubnetMaskCidr) } 
                    if ($SubnetMask) { $parametersAndArguments.Add('SubnetMask'$SubnetMask) } 
                    $parametersAndArguments.Add('Debug'$false) 
                    $parametersAndArguments.Add('Verbose'$false) 
 
                    if ($DefaultGateway) { $DefaultGateway = Remove-RvNetIpAddressLeadingZeros -IpAddress $DefaultGateway } 
 
                    # Obtaining required subnet mask 
                    $ipAddressDetails = Get-RvNetIpAddressDetails @parametersAndArguments 
                    if (!$ipAddressDetails) 
                    { 
                        throw 'IP address or subnet mask (IP address with CIDR, independent CIDR or subnet mask classes) was not provided.' 
                    } 
 
                    Write-Verbose '        - Setting static IP address...' 
                    Write-Verbose '            - Details:' 
                    Write-Verbose ('                - IP address:         {0}' -$ipAddressDetails.IpAddress) 
                    Write-Verbose ('                - Subnet mask - CIDR: {0}' -f [string]$ipAddressDetails.SubnetMaskCidr) 
                    Write-Verbose ('                - Subnet mask:        {0}' -$ipAddressDetails.SubnetMask) 
                    Write-Verbose ('                - Default gateway:    {0}' -$(if ($DefaultGateway) { $DefaultGateway } else { 'Not set' } )) 
                    Write-Verbose ('                - Dns server:         {0}' -$(if ($dnsServerItems) { ($dnsServerItems -join ', ') } else { 'Not set' } )) 
                    Write-Verbose '            - Configurations:' 
 
                    if (!$DefaultGateway -and $RemoveExistingDefaultGateway) 
                    { 
                        try 
                        { 
                            Write-Verbose '                - Setting DHCP in order to remove any existing default gateway that could be set on the defined NIC.' 
 
                            # Set-NetIPInterface -DHCP Enabled is not always working properly. 
                            $null = Invoke-Expression ('netsh interface ipv4 set address name={0} source=dhcp' -f [string]$InterfaceIndexItem-ErrorAction Stop 
 
                            Write-Verbose '                    - Results: Success' 
                        } 
                        catch 
                        { 
                            Write-Error 'It is not possible to set DHCP in order to remove default gateway. The currently processed NIC will be skipped.' 
                            continue settingIpAddresses 
                        } 
                    } 
 
                    if (!$dnsServerItems -and $RemoveExistingDnsServer) 
                    { 
                        try 
                        { 
                            Write-Verbose '                - Resetting DNS servers in order to remove any existing DNS servers that could be set on the defined NIC.' 
 
                            Set-DnsClientServerAddress -InterfaceIndex $InterfaceIndexItem -ResetServerAddresses -ErrorAction Stop 
 
                            Write-Verbose '                    - Results: Success' 
                        } 
                        catch 
                        { 
                            Write-Error 'It is not possible to reset DNS servers in order to remove existing DNS servers. The currently processed NIC will be skipped.' 
                            continue settingIpAddresses 
                        } 
                    } 
 
                    try 
                    { 
                        $nic = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.InterfaceIndex -eq $InterfaceIndexItem } 
 
                        Write-Verbose '                - Setting static IP address:' 
                        Write-Verbose '                    - Details:' 
                        Write-Verbose ('                        - IP address:  {0}' -$ipAddressDetails.IpAddress) 
                        Write-Verbose ('                        - Subnet mask: {0} (CIDR {1})' -$ipAddressDetails.SubnetMask, $ipAddressDetails.SubnetMaskCidr) 
 
                        $result = $nic.EnableStatic($ipAddressDetails.IpAddress, $ipAddressDetails.SubnetMask) 
 
                        Write-Verbose ('                    - Results: Return value: {0}' -f [string]$result.ReturnValue) 
                    } 
                    catch 
                    { 
                        Write-Error 'Error during setting static IP address. The currently processed NIC will be skipped.' 
                        continue settingIpAddresses 
                    } 
 
                    if ($DefaultGateway) 
                    { 
                        try 
                        { 
                            Write-Verbose ('                - Setting default gateway: ' + $DefaultGateway) 
 
                            $result = $nic.SetGateways($DefaultGateway# By default the metric is 1. 
 
                            Write-Verbose ('                    - Results: Return value: ' + [string]$result.ReturnValue) 
                        } 
                        catch 
                        { 
                            Write-Error 'Error during setting default gateway. The currently processed NIC will be skipped.' 
                            continue settingIpAddresses 
                        } 
                    } 
 
                    if ($dnsServerItems) 
                    { 
                        try 
                        { 
                            Write-Verbose ('                - Setting DNS server ({0}): {1}' -f [string]$dnsServerItems.Count, ($dnsServerItems -join ', ')) 
 
                            # Always working properly so no WMI needed. 
                            Set-DnsClientServerAddress -InterfaceIndex $InterfaceIndexItem -ServerAddresses $dnsServerItems -ErrorAction Stop 
 
                            Write-Verbose '                    - Results: Success' 
                        } 
                        catch 
                        { 
                            Write-Error 'Error during setting DNS server. The currently processed NIC will be skipped.' 
                            continue settingIpAddresses 
                        } 
                    } 
 
                    Write-Verbose '            - Overall results:' 
 
                    # Refresh of the information about the NIC (state could change during script run-time) 
                    $nicConnectionState = (Get-NetIPInterface -InterfaceIndex $InterfaceIndexItem).ConnectionState 
 
                    Write-Verbose ('                - NIC connection state: {0}' -$nicConnectionState) 
 
                    if ($nicConnectionState -eq 'Connected') 
                    { 
                        # Refresh of the information about the NIC (changed during script run-time) 
                        $nicResults = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.InterfaceIndex -eq $InterfaceIndexItem } 
                        Write-Verbose ('                - IP address:      {0}' -f ($nicResults.IpAddress -join ', ')) 
                        Write-Verbose ('                - Subnet mask:     {0}' -f ($nicResults.IPSubnet -join ', ')) 
                        Write-Verbose ('                - Default gateway: {0}' -f ($nicResults.DefaultIPGateway -join ', ')) 
                        Write-Verbose ('                - DNS servers:     {0}' -f ($nicResults.dnsServersearchorder -join ', ')) 
                    } 
                    else 
                    { 
                        # Refresh of the information about the NIC (changed during script run-time) 
                        $nicResults = Get-NetIPAddress -InterfaceIndex $InterfaceIndexItem -ErrorAction SilentlyContinue | 
                            Where-Object { $_.IPAddress -notlike '169.*' } 
 
                        if ($nicResults) 
                        { 
                            Write-Verbose ('                - IP address: {0}' -f ($nicResults.IpAddress -join ', ')) 
                        } 
                        else 
                        { 
                            Write-Warning 'No IP addresses. Are you assigning same static IP address to muliple NICs?' 
                        } 
                    } 
 
                    # Return 
                    $returnIpAddress = Get-NetIPAddress -IPAddress $ipAddressDetails.IpAddress -ErrorAction SilentlyContinue 
                    if ($returnIpAddress) 
                    { 
                        # Return 
                        $returnIpAddress 
                    } 
                    else 
                    { 
                        Write-Error 'It is not possible to load the set the IP address for output.' 
                    } 
                } 
            } 
        } 
    } 
 
    End 
    { 
        Write-Verbose '' 
        Write-Verbose '- Set-RvNetIpAddress: End' 
    } 
} 
 
 
 
Function Set-RvNetIpAddressDhcp 
{ 
    <# 
    .SYNOPSIS 
        More information in the help for Set-RvNetIpAddress function. 
 
    .DESCRIPTION 
        Developer 
            Developer: Rudolf Vesely, http://rudolfvesely.com/ 
            Copyright (c) Rudolf Vesely. All rights reserved 
            License: Free for private use only 
 
        Description 
            More information in the help for Set-RvNetIpAddress function. 
 
            Use: Get-Help Set-RvNetIpAddress 
    #> 
 
    [CmdletBinding( 
        SupportsShouldProcess = $true, 
        ConfirmImpact = 'Medium' 
    )] 
 
    Param 
    ( 
        [string]$IpAddress, 
        [int]$SubnetMaskCidr, 
        [string]$SubnetMask, 
        [string]$DefaultGateway, 
        [string[]]$DnsServer, 
        [int[]]$InterfaceIndex, 
        [string[]]$InterfaceAlias, 
        # [string]$Type, 
        [switch]$RemoveExistingDefaultGateway = $true, 
        [switch]$RemoveExistingDnsServer = $true, 
        [switch]$Force 
 
    ) 
 
    $parametersAndArguments = $PsBoundParameters 
    $parametersAndArguments.Add('Type''DHCP') 
    Set-RvNetIpAddress @parametersAndArguments 
} 
 
 
 
Function Set-RvNetIpAddressStatic 
{ 
    <# 
    .SYNOPSIS 
        More information in the help for Set-RvNetIpAddress function. 
 
    .DESCRIPTION 
        Developer 
            Developer: Rudolf Vesely, http://rudolfvesely.com/ 
            Copyright (c) Rudolf Vesely. All rights reserved 
            License: Free for private use only 
 
        Description 
            More information in the help for Set-RvNetIpAddress function. 
 
            Use: Get-Help Set-RvNetIpAddress 
    #> 
 
    [CmdletBinding( 
        SupportsShouldProcess = $true, 
        ConfirmImpact = 'Medium' 
    )] 
 
    Param 
    ( 
        [string]$IpAddress, 
        [int]$SubnetMaskCidr, 
        [string]$SubnetMask, 
        [string]$DefaultGateway, 
        [string[]]$DnsServer, 
        [int[]]$InterfaceIndex, 
        [string[]]$InterfaceAlias, 
        # [string]$Type, 
        [switch]$RemoveExistingDefaultGateway = $true, 
        [switch]$RemoveExistingDnsServer = $true, 
        [switch]$Force 
 
    ) 
 
    $parametersAndArguments = $PsBoundParameters 
    $parametersAndArguments.Add('Type''Static') 
    Set-RvNetIpAddress @parametersAndArguments 
}



И более простой для включения DHCP клиента

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration `
| where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$NIC.EnableDHCP()
$NIC.SetDNSServerSearchOrder()
}