Скрипты Windows PowerShell для сетевых настроек

3738
Скрипты Windows PowerShell для сетевых настроек
Скрипты Windows PowerShell для сетевых настроек

Включение DHCP

param($computer="localhost",$action,$help)
 
function funHelp()
{
$helpText=@"
DESCRIPTION:
NAME: WorkWithDHCP.ps1
Works with DHCP settings on a local or remote machine.
 
PARAMETERS: 
-computerName Specifies the name of the computer upon which to run the script
-action <q(uery) e(nable) r(elease) rr(release/renew)  action to perform
-help   prints help file
 
SYNTAX:
WorkWithDHCP.ps1 -q "yes" -computer MunichServer
 
Queries DHCP settings on a computer named MunichServer
 
WorkWithDHCP.ps1 -action e
 
enables DHCP on local computer
 
WorkWithDHCP.ps1 -action r
 
Releases the DHCP address on the local machine
 
WorkWithDHCP.ps1 -action rr
 
Releases and then renews the DHCP address on the local machine
 
WorkWithDHCP.ps1 -help ?
 
Displays the help topic for the script
 
"@
$helpText
exit
}
 
function FunEvalRTN($rtn)
{ 
Switch ($rtn.returnvalue) 
  { 
   0 { Write-Host -foregroundcolor green "No errors for $strCall" }
   82 { Write-Host -foregroundcolor red "$strCall reports" `
       " Unable to renew DHCP lease" }
   83 { Write-Host -ForegroundColor red "$strCall reports" `
       " Unable to release DHCP lease" }
   91 { Write-Host -ForegroundColor red "$strCall reports" `
         " access denied"}
   DEFAULT { Write-Host -ForegroundColor red "$strCall service reports" `
             " ERROR $($rtn.returnValue)" }
  }
  $rtn=$strCall=$null
}
 
 
if($help) { funhelp }
$global:RTN = $null
if(!$action) { $action="q" }
 
$objWMI = Get-WmiObject -Class win32_networkadapterconfiguration `
 -computer $computer -filter "ipenabled = 'true'"
 
Switch($action)
{ 
 "e" { 
      $rtn = $objWMI.EnableDHCP() ; 
      $strCall = "Enable DHCP" ; 
      FunEvalRTN($rtn) 
     }
  "r" { 
      $rtn = $objWMI.ReleaseDHCPLease() ; 
      $strCall = "Release DHCP address" ; 
      FunEvalRTN($rtn) 
     }
 "rr" { 
      $rtn = $objWMI.RenewDHCPLease() ; 
      $strCall = "Release and Renew DHCP address" ; 
      FunEvalRTN($rtn) 
     }
 "q" {
      "DHCP Server: $($objWMI.dhcpserver)"
       "Lease obtained: " + [Management.ManagementDatetimeConverter]::`
        todatetime($objWMI.DHCPleaseObtained)
       "Lease expires: " + [Management.ManagementDatetimeConverter]::`
       todatetime($objWMI.DHCPleaseExpires)
     }
     
}

 

Вывод информации о конфигурации адаптеров (локальных и на удаленных хостах)

param($computer="localhost",$query,$help)
function funHelp()
{
$helpText=@"
DESCRIPTION:
NAME: GetNetAdapterConfig.ps1
Produces a listing of network adapter configuration information
on a local or remote machine.
 
PARAMETERS: 
-computer Specifies the name of the computer to run the script
-help     prints help file
-query    the type of query < ip, dns, dhcp, all >
SYNTAX:
GetNetAdapterConfig.ps1 -computerName MunichServer
 
Lists default network adapter configuration on a 
computer named MunichServer
 
GetNetAdapterConfig.ps1 -computerName MunichServer -query IP
 
Lists IPaddress, IPsubnet, DefaultIPgateway, MACAddress 
on a computer named MunichServer
 
GetNetAdapterConfig.ps1 -computerName MunichServer -query DNS
 
Lists DNSDomain, DNSDomainSuffixSearchOrder, DNSServerSearchOrder, 
DomainDNSRegistrationEnabled on a computer named MunichServer
 
GetNetAdapterConfig.ps1 -computerName MunichServer -query DHCP
 
Lists Index,DHCPEnabled, DHCPLeaseExpires, DHCPLeaseObtained, 
DHCPServer on a computer named MunichServer
 
GetNetAdapterConfig.ps1 -computerName MunichServer -query ALL
 
Lists all network adapter configuration information on a computer 
named MunichServer
 
GetNetAdapterConfig.ps1 -help ?
 
Prints the help topic for the script
 
"@
$helpText
exit
}
 
if($help) { "Printing help now..." ; funHelp }
 
$class="win32_networkadapterconfiguration"
$IPproperty="IPaddress, IPsubnet, DefaultIPgateway, MACAddress"
$dnsProperty="DNSDomain, DNSDomainSuffixSearchOrder, `
 DNSServerSearchOrder, DomainDNSRegistrationEnabled"
$dhcpProperty="Index,DHCPEnabled, DHCPLeaseExpires, `
 DHCPLeaseObtained, DHCPServer"
 
if($query)
{
 switch($query)
 {
  "ip"    { $query="Select $IPproperty from $class" }
  "dns"   { $query="Select $dnsProperty from $class" }
  "dhcp"  { $query="Select $dhcpProperty from $class" }
  "all"   { 
            $query = "Select * from $class" ; `
            Get-WmiObject -Query $query | format-list * ; 
            exit
         }  
  DEFAULT { 
           $query = "Select * from $class" ; `
           Get-WmiObject -Query $query ; exit  
          }
 }
}
ELSE
 { 
  $query = "Select * from $class" ; `
  Get-WmiObject -Query $query ; exit 
 }
 
Get-WmiObject -query $query | format-table [a-z]* -AutoSize

 

Вывод информации о настройках брандмауэра

$fwCfg = netsh firewall show config
$enable=$disable=$null
 
switch -regex ($fwCfg)
 {
  "enable"
    { 
     $enable+=$switch.current+"`n"
    }
  "disable"
    { 
     $disable+=$switch.current+"`n"
    }
 }
 
Write-Host -ForegroundColor cyan `
  "Firewall configuration on $env:computername"
Write-Host -ForegroundColor green `
  "The following are enabled`n"
  $enable
Write-Host -ForegroundColor red `
  "The following are disabled`n"
  $disable

 

Задание статического IP

param($computer="localhost",$q,$ip,$sm,$dg,$dns,$help)
 
function funHelp()
{
$helpText=@"
DESCRIPTION:
NAME: SetStaticIP.ps1
Sets a static IP address on a local or remote machine.
 
PARAMETERS: 
-computerName Specifies the name of the computer upon which to run the script
-q            Queries all IP bound network adapters
-ip           IP address to use
-sm           Subnet mask to use
-dg           Default gateway to use
-dns          Dns server to use
-help         prints help file
 
SYNTAX:
SetStaticIP.ps1 -q "yes" -computer MunichServer
 
Lists all the network adapters bound to IP on a computer named MunichServer
 
SetStaticIP.ps1 
 
Lists all the network adapters bound to IP on local computer
 
SetStaticIP.ps1 -ip "10.0.0.1" -sm "255.0.0.0" -dg "10.0.0.5" -dns "10.0.0.2"
 
Sets the Ip address to 10.0.0.1 and the subnet mask to 255.0.0.0 and the default
Gateway to 10.0.0.5 with a dns server of 10.0.0.2 on the local machine
 
SetStaticIP.ps1 -help ?
 
Displays the help topic for the script
 
"@
$helpText
exit
}
 
function FunEvalRTN($rtn)
{ 
Switch ($rtn.returnvalue) 
  { 
   0 { Write-Host -foregroundcolor green "No errors for $strCall" }
   66 { Write-Host -foregroundcolor red "$strCall reports" `
       " invalid subnetMask" }
   70 { Write-Host -ForegroundColor red "$strCall reports" `
       " invalid IP" }
   71 { Write-Host -ForegroundColor red "$strCall reports" `
         " invalid gateway" }
   91 { Write-Host -ForegroundColor red "$strCall reports" `
         " access denied"}
   96 { Write-Host -ForegroundColor red "$strCall reports" `
         " unable to contact dns server"}
   DEFAULT { Write-Host -ForegroundColor red "$strCall service reports" `
             " ERROR $($rtn.returnValue)" }
  }
  $rtn=$strCall=$null
}
 
 
if($help) { funhelp }
 
if($q)
{ 
 Get-WmiObject -Class win32_networkadapterconfiguration `
 -computer $computer -filter "ipenabled = 'true'"
exit
}
 
if(!$ip)  { funhelp }
if(!$sm)  { funhelp }
if(!$dg)  { funhelp }
if(!$dns) { funhelp }
 
$global:RTN = $null
$metric = [int32[]]1
$objWMI = Get-WmiObject -Class win32_networkadapterconfiguration `
 -computer $computer -filter "ipenabled = 'true'"
 
$RTN=$objwmi.EnableStatic($ip, $sm)
$strCall="enable static IP and subnet mask"
 
FunEvalRTN($rtn)
$RTN=$objwmi.SetGateways($dg, $metric)
$strCall="enable set default gateway and metric"
FunEvalRTN($rtn)
$RTN=$objwmi.SetDNSServerSearchOrder($dns)
$strCall="Set the dns server search order"
FunEvalRTN($rtn)

 

Идентификация подсоединенных сетевых адаптеров

$computer="localhost"
$connected=2
Get-WmiObject -Class win32_networkadapter -computername $computer `
-filter "netconnectionstatus = $connected" |
foreach-object `
 {
   Get-WmiObject -Class win32_networkadapterconfiguration `
   -computername $computer -filter "Index = $($_.deviceID)"
 }

 

Обнаружение нескольких сетевых адаптеров

Get-WmiObject -Class win32_networkadapter |
format-table -Property name, interfaceIndex, `
adapterType, macAddress -autosize

 

Отчет о состоянии сетевых адаптеров

param($computer="localhost",$help)
function funStatus($status)
{
 switch($status)
  {
   0 { " Disconnected" }
   1 { " Connecting" } 
   2 { " Connected" }  
   3 { " Disconnecting" } 
   4 { " Hardware not present" } 
   5 { " Hardware disabled" } 
   6 { " Hardware malfunction" } 
   7 { " Media disconnected" } 
   8 { " Authenticating" } 
   9 { " Authentication succeeded" } 
   10 { " Authentication failed" } 
  }
 
}
 
function funHelp()
{
$helpText=@"
DESCRIPTION:
NAME: GetNetAdapterStatus.ps1
Produces a listing of network adapters and status on a local or remote machine.
 
PARAMETERS: 
-computerName Specifies the name of the computer upon which to run the script
-help         prints help file
 
SYNTAX:
GetNetAdapterStatus.ps1 -computer MunichServer
 
Lists all the network adapters and status on a computer named MunichServer
 
GetNetAdapterStatus.ps1 
 
Lists all the network adapters and status on local computer
 
GetNetAdapterStatus.ps1 -help ?
 
Displays the help topic for the script
 
"@
$helpText
exit
}
 
function funline ($strIN)
{
 $num = $strIN.length
 for($i=1 ; $i -le $num ; $i++)
  { $funline = $funline + "=" }
    Write-Host -ForegroundColor yellow $strIN 
    Write-Host -ForegroundColor darkYellow $funline
}
 
if($help) { "Printing help now..." ; funHelp }
 
$objWMI=Get-WmiObject -Class win32_networkadapter -computer $computer
 
funline("Network adapters and status on $computer")
foreach($net in $objWMI)
{
 Write-Host "$($net.name)"
  funstatus($net.netconnectionstatus)
}

 

Примеры задания настроек брандмауэра

Включение удаленного администрирования

$errRTN=netsh firewall set service remoteAdmin enable
if($errRTN -match 'ok')
   { Write-Host -ForegroundColor green "Remote admin enabled" }
   ELSEIF($errRTN -match 'requires elevation')
   { Write-Host -ForegroundColor red "Remote admin not enabled" `
     "The operation requries admin rights"}
    ELSE
     { Write-Host -ForegroundColor red "Remote admin not enabled" `
       "The error reported was $errRTN" }

Включение общих папок

$errRTN=netsh firewall set service fileAndPrint enable
if($errRTN -match 'ok')
   { Write-Host -ForegroundColor green "Shared folders enabled" }
   ELSEIF($errRTN -match 'requires elevation')
   { Write-Host -ForegroundColor red "Shared folders not enabled" `
     "The operation requries admin rights"}
    ELSE
     { Write-Host -ForegroundColor red "Shared folders not enabled" `
       "The error reported was $errRTN" }

 

Экспорт параметров адаптера в Excel

$strPath="c:\fso\netAdapter.xls"
$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.Workbooks.Add()
$sheet=$workbook.worksheets.item(1)
 
$x=2
 
$Computer = $env:computerName
$objWMIService = Get-WmiObject -class win32_NetworkAdapter `
   -computer $Computer
for($b=1 ; $b -le 10 ; $b++)
  {$sheet.Cells.item(1,$b).font.bold=$true}
$sheet.Cells.item(1,1)=("Name of Adapter")
$sheet.Cells.item(1,2)=("Interface Index")
$sheet.Cells.item(1,3)=("Index")
$sheet.Cells.item(1,4)=("DeviceID")
$sheet.Cells.item(1,5)=("AdapterType")
$sheet.Cells.item(1,6)=("MacAddress")
$sheet.Cells.item(1,7)=("netconnectionid")
$sheet.Cells.item(1,8)=("NetConnectionStatus")
$sheet.Cells.item(1,9)=("NetworkAddresses")
$sheet.Cells.item(1,10)=("PermanentAddress")
 
ForEach ($objNet in $objWMIService)
{
    $sheet.Cells.item($x, 1)=($objNet.Name)
    $sheet.Cells.item($x, 2)=($objNet.InterfaceIndex)
    $sheet.Cells.item($x, 3)=($objNet.index)
    $sheet.Cells.item($x, 4)=($objNet.DeviceID)
    $sheet.Cells.item($x, 5)=($objNet.adapterType)
    $sheet.Cells.item($x, 6)=($objNet.MacAddress)
    $sheet.Cells.item($x,7)=($objNet.netconnectionid)
    $sheet.Cells.item($x,8)=($objNet.NetConnectionStatus)
    $sheet.Cells.item($x,9)=($objNet.NetworkAddresses)
    $sheet.Cells.item($x,10)=($objNet.PermanentAddress)
 
    If($objNet.AdapterType -notMatch 'ethernet')
    {
     $sheet.Cells.item($x,5).font.colorIndex=3 # 32 is blue 16 silver/gray 8 is Aqua, 4 is green, 3 is red
     $sheet.Cells.item($x,5).font.bold=$true
    }
    $x++
}
 $range = $sheet.usedRange
 $range.EntireColumn.AutoFit()
 
IF(Test-Path $strPath)
  { 
   Remove-Item $strPath
   $objExcel.ActiveWorkbook.SaveAs($strPath)
  }
ELSE
  {
   $objExcel.ActiveWorkbook.SaveAs($strPath)
  }