EBobkunov

setnet.ps1

Sep 17th, 2026
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 8.50 KB | Source Code | 0 0
  1. <#
  2. .SYNOPSIS
  3.     Настройка сетевого интерфейса средствами PowerShell.
  4.  
  5. .DESCRIPTION
  6.     Скрипт умеет: перевести интерфейс на DHCP, задать статические настройки,
  7.     показать текущую конфигурацию и вывести сведения об адаптере
  8.     (модель, наличие линка, скорость и режим работы).
  9.  
  10. .PARAMETER Mode
  11.     dhcp | static | show | info
  12.  
  13. .EXAMPLE
  14.     .\setnet.ps1 -Mode dhcp -Interface Ethernet
  15.  
  16. .EXAMPLE
  17.     .\setnet.ps1 -Mode static -Interface Ethernet -IPAddress 192.168.10.50 `
  18.                  -PrefixLength 24 -Gateway 192.168.10.1 -DNS 8.8.8.8,1.1.1.1
  19.  
  20. .EXAMPLE
  21.     .\setnet.ps1 -Mode info -Interface Ethernet
  22.  
  23. .EXAMPLE
  24.     .\setnet.ps1            # без параметров - интерактивное меню
  25. #>
  26.  
  27. [CmdletBinding()]
  28. param(
  29.     [ValidateSet('dhcp', 'static', 'show', 'info')]
  30.     [string]   $Mode,
  31.     [string]   $Interface,
  32.     [string]   $IPAddress,
  33.     [int]      $PrefixLength = 24,
  34.     [string]   $Gateway,
  35.     [string[]] $DNS
  36. )
  37.  
  38. $ErrorActionPreference = 'Stop'
  39.  
  40. # --------------------------------------------------------------------------
  41. function Test-Admin {
  42.     $id = [Security.Principal.WindowsIdentity]::GetCurrent()
  43.     $pr = New-Object Security.Principal.WindowsPrincipal($id)
  44.     return $pr.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
  45. }
  46.  
  47. function Select-Interface {
  48.     Write-Host "`n============ Доступные адаптеры ============" -ForegroundColor Yellow
  49.     Get-NetAdapter | Format-Table Name, InterfaceDescription, Status, LinkSpeed -AutoSize | Out-Host
  50.     do {
  51.         $name = Read-Host 'Имя интерфейса (например Ethernet)'
  52.     } while (-not $name)
  53.     return $name
  54. }
  55.  
  56. function Set-ModeDhcp {
  57.     param([string] $If)
  58.  
  59.     Write-Host "[*] Включаю автоматическое получение адреса на '$If' ..." -ForegroundColor Cyan
  60.  
  61.     # снимаем статику, иначе New-NetIPAddress/DHCP конфликтуют с прежним адресом
  62.     Remove-NetIPAddress -InterfaceAlias $If -AddressFamily IPv4 -Confirm:$false -ErrorAction SilentlyContinue
  63.     Remove-NetRoute     -InterfaceAlias $If -DestinationPrefix '0.0.0.0/0' -Confirm:$false -ErrorAction SilentlyContinue
  64.  
  65.     Set-NetIPInterface        -InterfaceAlias $If -Dhcp Enabled
  66.     Set-DnsClientServerAddress -InterfaceAlias $If -ResetServerAddresses
  67.  
  68.     Start-Sleep -Seconds 2
  69.     ipconfig /renew "$If" | Out-Null
  70.  
  71.     Write-Host '[OK] Интерфейс переведён на DHCP.' -ForegroundColor Green
  72. }
  73.  
  74. function Set-ModeStatic {
  75.     param(
  76.         [string]   $If,
  77.         [string]   $Ip,
  78.         [int]      $Prefix,
  79.         [string]   $Gw,
  80.         [string[]] $Dns
  81.     )
  82.  
  83.     Write-Host "[*] Применяю статические настройки на '$If' ..." -ForegroundColor Cyan
  84.  
  85.     Set-NetIPInterface  -InterfaceAlias $If -Dhcp Disabled
  86.     Remove-NetIPAddress -InterfaceAlias $If -AddressFamily IPv4 -Confirm:$false -ErrorAction SilentlyContinue
  87.     Remove-NetRoute     -InterfaceAlias $If -DestinationPrefix '0.0.0.0/0' -Confirm:$false -ErrorAction SilentlyContinue
  88.  
  89.     if ($Gw) {
  90.         New-NetIPAddress -InterfaceAlias $If -IPAddress $Ip -PrefixLength $Prefix -DefaultGateway $Gw | Out-Null
  91.     }
  92.     else {
  93.         New-NetIPAddress -InterfaceAlias $If -IPAddress $Ip -PrefixLength $Prefix | Out-Null
  94.     }
  95.  
  96.     if ($Dns) {
  97.         Set-DnsClientServerAddress -InterfaceAlias $If -ServerAddresses $Dns
  98.     }
  99.  
  100.     Write-Host '[OK] Статические настройки применены.' -ForegroundColor Green
  101. }
  102.  
  103. function Show-Config {
  104.     param([string] $If)
  105.  
  106.     Write-Host "`n============ Конфигурация '$If' ============" -ForegroundColor Yellow
  107.     Get-NetIPConfiguration -InterfaceAlias $If -Detailed | Format-List | Out-Host
  108.  
  109.     Write-Host '============ IP-адреса ============' -ForegroundColor Yellow
  110.     Get-NetIPAddress -InterfaceAlias $If -AddressFamily IPv4 |
  111.         Format-Table IPAddress, PrefixLength, PrefixOrigin, SuffixOrigin, AddressState -AutoSize | Out-Host
  112.  
  113.     Write-Host '============ Маршрут по умолчанию ============' -ForegroundColor Yellow
  114.     Get-NetRoute -InterfaceAlias $If -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue |
  115.         Format-Table DestinationPrefix, NextHop, RouteMetric -AutoSize | Out-Host
  116.  
  117.     Write-Host '============ DNS-серверы ============' -ForegroundColor Yellow
  118.     Get-DnsClientServerAddress -InterfaceAlias $If -AddressFamily IPv4 |
  119.         Format-Table InterfaceAlias, ServerAddresses -AutoSize | Out-Host
  120. }
  121.  
  122. function Show-AdapterInfo {
  123.     param([string] $If)
  124.  
  125.     $a = Get-NetAdapter -Name $If
  126.  
  127.     # режим дуплекса, как его сообщает драйвер адаптера
  128.     $adv = Get-NetAdapterAdvancedProperty -Name $If -ErrorAction SilentlyContinue |
  129.            Where-Object { $_.DisplayName -match 'Duplex|Дуплекс|Speed|Скорость' } |
  130.            Select-Object -First 1
  131.  
  132.     Write-Host "`n============ Сведения об адаптере '$If' ============" -ForegroundColor Yellow
  133.  
  134.     [pscustomobject][ordered]@{
  135.         'Имя соединения'        = $a.Name
  136.         'Модель (описание)'     = $a.InterfaceDescription
  137.         'MAC-адрес'             = $a.MacAddress
  138.         'Состояние'             = $a.Status
  139.         'Физический линк'       = $a.MediaConnectionState
  140.         'Скорость'              = $a.LinkSpeed
  141.         'Полный дуплекс'        = $a.FullDuplex
  142.         'Режим по данным драйвера' = $(if ($adv) { "$($adv.DisplayName) = $($adv.DisplayValue)" } else { 'параметр не публикуется драйвером' })
  143.         'MTU'                   = $a.MtuSize
  144.         'Тип среды'             = $a.MediaType
  145.         'Драйвер'               = "$($a.DriverFileName) $($a.DriverVersion)"
  146.     } | Format-List | Out-Host
  147. }
  148.  
  149. # --------------------------------------------------------------------------
  150. if (-not (Test-Admin)) {
  151.     Write-Warning 'Нужны права администратора. Запустите PowerShell от имени администратора.'
  152.     exit 1
  153. }
  154.  
  155. if (-not $Interface) { $Interface = Select-Interface }
  156.  
  157. if (-not $Mode) {
  158.     do {
  159.         Write-Host "`n============ Что сделать? ============" -ForegroundColor Yellow
  160.         Write-Host '  1 - Получить настройки автоматически (DHCP)'
  161.         Write-Host '  2 - Задать настройки вручную (статически)'
  162.         Write-Host '  3 - Показать текущие настройки'
  163.         Write-Host '  4 - Сведения об адаптере (модель, линк, скорость, дуплекс)'
  164.         Write-Host '  0 - Выход'
  165.         $choice = Read-Host "`nВаш выбор"
  166.  
  167.         switch ($choice) {
  168.             '1' { Set-ModeDhcp -If $Interface; Show-Config -If $Interface }
  169.             '2' {
  170.                 $IPAddress    = Read-Host 'IP-адрес'
  171.                 $PrefixLength = [int](Read-Host 'Длина префикса (24 = 255.255.255.0)')
  172.                 $Gateway      = Read-Host 'Основной шлюз'
  173.                 $dnsRaw       = Read-Host 'DNS-серверы через запятую (Enter - пропустить)'
  174.                 $DNS          = if ($dnsRaw) { $dnsRaw -split '\s*,\s*' } else { $null }
  175.  
  176.                 Set-ModeStatic -If $Interface -Ip $IPAddress -Prefix $PrefixLength -Gw $Gateway -Dns $DNS
  177.                 Show-Config -If $Interface
  178.             }
  179.             '3' { Show-Config      -If $Interface }
  180.             '4' { Show-AdapterInfo -If $Interface }
  181.             '0' { break }
  182.             default { Write-Host '[!] Нет такого пункта.' -ForegroundColor Red }
  183.         }
  184.     } while ($choice -ne '0')
  185.  
  186.     exit 0
  187. }
  188.  
  189. switch ($Mode) {
  190.     'dhcp' { Set-ModeDhcp -If $Interface; Show-Config -If $Interface }
  191.     'static' {
  192.         if (-not $IPAddress) { throw 'Для режима static обязателен параметр -IPAddress' }
  193.         Set-ModeStatic -If $Interface -Ip $IPAddress -Prefix $PrefixLength -Gw $Gateway -Dns $DNS
  194.         Show-Config -If $Interface
  195.     }
  196.     'show' { Show-Config      -If $Interface }
  197.     'info' { Show-AdapterInfo -If $Interface }
  198. }
  199.  
Advertisement
Add Comment
Please, Sign In to add comment