Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Настройка сетевого интерфейса средствами PowerShell.
- .DESCRIPTION
- Скрипт умеет: перевести интерфейс на DHCP, задать статические настройки,
- показать текущую конфигурацию и вывести сведения об адаптере
- (модель, наличие линка, скорость и режим работы).
- .PARAMETER Mode
- dhcp | static | show | info
- .EXAMPLE
- .\setnet.ps1 -Mode dhcp -Interface Ethernet
- .EXAMPLE
- .\setnet.ps1 -Mode static -Interface Ethernet -IPAddress 192.168.10.50 `
- -PrefixLength 24 -Gateway 192.168.10.1 -DNS 8.8.8.8,1.1.1.1
- .EXAMPLE
- .\setnet.ps1 -Mode info -Interface Ethernet
- .EXAMPLE
- .\setnet.ps1 # без параметров - интерактивное меню
- #>
- [CmdletBinding()]
- param(
- [ValidateSet('dhcp', 'static', 'show', 'info')]
- [string] $Mode,
- [string] $Interface,
- [string] $IPAddress,
- [int] $PrefixLength = 24,
- [string] $Gateway,
- [string[]] $DNS
- )
- $ErrorActionPreference = 'Stop'
- # --------------------------------------------------------------------------
- function Test-Admin {
- $id = [Security.Principal.WindowsIdentity]::GetCurrent()
- $pr = New-Object Security.Principal.WindowsPrincipal($id)
- return $pr.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
- }
- function Select-Interface {
- Write-Host "`n============ Доступные адаптеры ============" -ForegroundColor Yellow
- Get-NetAdapter | Format-Table Name, InterfaceDescription, Status, LinkSpeed -AutoSize | Out-Host
- do {
- $name = Read-Host 'Имя интерфейса (например Ethernet)'
- } while (-not $name)
- return $name
- }
- function Set-ModeDhcp {
- param([string] $If)
- Write-Host "[*] Включаю автоматическое получение адреса на '$If' ..." -ForegroundColor Cyan
- # снимаем статику, иначе New-NetIPAddress/DHCP конфликтуют с прежним адресом
- Remove-NetIPAddress -InterfaceAlias $If -AddressFamily IPv4 -Confirm:$false -ErrorAction SilentlyContinue
- Remove-NetRoute -InterfaceAlias $If -DestinationPrefix '0.0.0.0/0' -Confirm:$false -ErrorAction SilentlyContinue
- Set-NetIPInterface -InterfaceAlias $If -Dhcp Enabled
- Set-DnsClientServerAddress -InterfaceAlias $If -ResetServerAddresses
- Start-Sleep -Seconds 2
- ipconfig /renew "$If" | Out-Null
- Write-Host '[OK] Интерфейс переведён на DHCP.' -ForegroundColor Green
- }
- function Set-ModeStatic {
- param(
- [string] $If,
- [string] $Ip,
- [int] $Prefix,
- [string] $Gw,
- [string[]] $Dns
- )
- Write-Host "[*] Применяю статические настройки на '$If' ..." -ForegroundColor Cyan
- Set-NetIPInterface -InterfaceAlias $If -Dhcp Disabled
- Remove-NetIPAddress -InterfaceAlias $If -AddressFamily IPv4 -Confirm:$false -ErrorAction SilentlyContinue
- Remove-NetRoute -InterfaceAlias $If -DestinationPrefix '0.0.0.0/0' -Confirm:$false -ErrorAction SilentlyContinue
- if ($Gw) {
- New-NetIPAddress -InterfaceAlias $If -IPAddress $Ip -PrefixLength $Prefix -DefaultGateway $Gw | Out-Null
- }
- else {
- New-NetIPAddress -InterfaceAlias $If -IPAddress $Ip -PrefixLength $Prefix | Out-Null
- }
- if ($Dns) {
- Set-DnsClientServerAddress -InterfaceAlias $If -ServerAddresses $Dns
- }
- Write-Host '[OK] Статические настройки применены.' -ForegroundColor Green
- }
- function Show-Config {
- param([string] $If)
- Write-Host "`n============ Конфигурация '$If' ============" -ForegroundColor Yellow
- Get-NetIPConfiguration -InterfaceAlias $If -Detailed | Format-List | Out-Host
- Write-Host '============ IP-адреса ============' -ForegroundColor Yellow
- Get-NetIPAddress -InterfaceAlias $If -AddressFamily IPv4 |
- Format-Table IPAddress, PrefixLength, PrefixOrigin, SuffixOrigin, AddressState -AutoSize | Out-Host
- Write-Host '============ Маршрут по умолчанию ============' -ForegroundColor Yellow
- Get-NetRoute -InterfaceAlias $If -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue |
- Format-Table DestinationPrefix, NextHop, RouteMetric -AutoSize | Out-Host
- Write-Host '============ DNS-серверы ============' -ForegroundColor Yellow
- Get-DnsClientServerAddress -InterfaceAlias $If -AddressFamily IPv4 |
- Format-Table InterfaceAlias, ServerAddresses -AutoSize | Out-Host
- }
- function Show-AdapterInfo {
- param([string] $If)
- $a = Get-NetAdapter -Name $If
- # режим дуплекса, как его сообщает драйвер адаптера
- $adv = Get-NetAdapterAdvancedProperty -Name $If -ErrorAction SilentlyContinue |
- Where-Object { $_.DisplayName -match 'Duplex|Дуплекс|Speed|Скорость' } |
- Select-Object -First 1
- Write-Host "`n============ Сведения об адаптере '$If' ============" -ForegroundColor Yellow
- [pscustomobject][ordered]@{
- 'Имя соединения' = $a.Name
- 'Модель (описание)' = $a.InterfaceDescription
- 'MAC-адрес' = $a.MacAddress
- 'Состояние' = $a.Status
- 'Физический линк' = $a.MediaConnectionState
- 'Скорость' = $a.LinkSpeed
- 'Полный дуплекс' = $a.FullDuplex
- 'Режим по данным драйвера' = $(if ($adv) { "$($adv.DisplayName) = $($adv.DisplayValue)" } else { 'параметр не публикуется драйвером' })
- 'MTU' = $a.MtuSize
- 'Тип среды' = $a.MediaType
- 'Драйвер' = "$($a.DriverFileName) $($a.DriverVersion)"
- } | Format-List | Out-Host
- }
- # --------------------------------------------------------------------------
- if (-not (Test-Admin)) {
- Write-Warning 'Нужны права администратора. Запустите PowerShell от имени администратора.'
- exit 1
- }
- if (-not $Interface) { $Interface = Select-Interface }
- if (-not $Mode) {
- do {
- Write-Host "`n============ Что сделать? ============" -ForegroundColor Yellow
- Write-Host ' 1 - Получить настройки автоматически (DHCP)'
- Write-Host ' 2 - Задать настройки вручную (статически)'
- Write-Host ' 3 - Показать текущие настройки'
- Write-Host ' 4 - Сведения об адаптере (модель, линк, скорость, дуплекс)'
- Write-Host ' 0 - Выход'
- $choice = Read-Host "`nВаш выбор"
- switch ($choice) {
- '1' { Set-ModeDhcp -If $Interface; Show-Config -If $Interface }
- '2' {
- $IPAddress = Read-Host 'IP-адрес'
- $PrefixLength = [int](Read-Host 'Длина префикса (24 = 255.255.255.0)')
- $Gateway = Read-Host 'Основной шлюз'
- $dnsRaw = Read-Host 'DNS-серверы через запятую (Enter - пропустить)'
- $DNS = if ($dnsRaw) { $dnsRaw -split '\s*,\s*' } else { $null }
- Set-ModeStatic -If $Interface -Ip $IPAddress -Prefix $PrefixLength -Gw $Gateway -Dns $DNS
- Show-Config -If $Interface
- }
- '3' { Show-Config -If $Interface }
- '4' { Show-AdapterInfo -If $Interface }
- '0' { break }
- default { Write-Host '[!] Нет такого пункта.' -ForegroundColor Red }
- }
- } while ($choice -ne '0')
- exit 0
- }
- switch ($Mode) {
- 'dhcp' { Set-ModeDhcp -If $Interface; Show-Config -If $Interface }
- 'static' {
- if (-not $IPAddress) { throw 'Для режима static обязателен параметр -IPAddress' }
- Set-ModeStatic -If $Interface -Ip $IPAddress -Prefix $PrefixLength -Gw $Gateway -Dns $DNS
- Show-Config -If $Interface
- }
- 'show' { Show-Config -If $Interface }
- 'info' { Show-AdapterInfo -If $Interface }
- }
Advertisement
Add Comment
Please, Sign In to add comment