• EnglishSpanishGermanFrenchPolishChinese (Traditional)


EnglishSpanishGermanFrenchPolishChinese (Traditional)

Operating systems, scripting, PowerShell and security

Operating systems, software development, scripting, PowerShell tips, network and security

Menú principal
  • Categorías
  • Cursos
  • Libro de PowerShell
  • Lo mejor
  • Lo último
  • Proyectos
  • Contactar
Ir al contenido

Ejercicios de PowerShell: ordenar direcciones IP remotamente y crear un disco virtual (Invoke-Command)

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# Necesita winrm, el módulo TCPServer e Hyper-V habilitado
 
$menu=@"
1 Ordenar IPs
2 Crear VHD
S Salir
Seleccione una tarea o pulse S para salir
"@
 
$equipos = Get-ADComputer -Filter * | select -ExpandProperty name
 
Function Invoke-Menu {
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter your menu text")]
[ValidateNotNullOrEmpty()]
[string]$Menu,
[Parameter(Position=1)]
[ValidateNotNullOrEmpty()]
[string]$Title = "My Menu",
[Alias("cls")]
[switch]$ClearScreen
)
#clear the screen if requested
if ($ClearScreen) {
Clear-Host
}
#build the menu prompt
$menuPrompt = $title
#add a return
$menuprompt+="`n"
#add an underline
$menuprompt+="-"*$title.Length
#add another return
$menuprompt+="`n"
#add the menu
$menuPrompt+=$menu
Read-Host -Prompt $menuprompt
}
 
Do {
    Switch (Invoke-Menu -menu $menu -title "Tareas de administración" -clear) {
     "1" {$i = 20
           $equipos | where {$_ -notmatch "SERVER"} | %{
            $ipn = "192.168.1." + $i++
            Write-Host "Cambiando IP de $_" -ForegroundColor Green
             sleep -seconds 2
                Enter-PSSession -ComputerName $_
                Invoke-Command -ComputerName $_ -ScriptBlock {
                    $ipa = Get-NetIPAddress -InterfaceIndex 7 -AddressFamily IPv4 | select -ExpandProperty IPAddress
                    New-NetIPAddress -IPAddress $using:ipn -AddressFamily IPv4 -InterfaceIndex 7 -PrefixLength 24
                    Remove-NetIPAddress -IPAddress "$ipa" -Confirm:$False
                } -AsJob
                Exit-PSSession
                }
             Clear-DnsClientCache
             Read-Host "IPs cambiadas con éxito, presione ENTER para volver al menú"
         }
     "2" {Write-Host "Por favor, especifique los parámetros deseados" -ForegroundColor Green
          sleep -seconds 2
 
            $cliente = Read-Host "Introduzca el equipo donde quiere crear el VHD"
            $nombre = Read-Host "Introduzca el nombre del disco"
            $archivo = "C:\" + $nombre + ".vhdx"
            $letra = 65..90 | %{[char]$_} | Where-Object {$_ -notin (Get-Partition | select -ExpandProperty DriveLetter)} | Get-Random
            $capacidad = Read-Host "Introduzca la capacidad en MB"
            $secpasswd = ConvertTo-SecureString "Escarabajo.11" -AsPlainText -Force
            $mycreds = New-Object System.Management.Automation.PSCredential ("red\administrador", $secpasswd)
 
            Invoke-TCPServer -Computername $cliente -Port 1655 `
            -Credential ($mycreds) -Verbose
 
            $command = @"
            New-VHD -Path $archivo -SizeBytes ([int]$capacidad* 1MB)
            Mount-VHD $archivo -Passthru | Initialize-Disk -PassThru |
            New-Partition -UseMaximumSize -DriveLetter "$letra"   |
            Format-Volume -FileSystem NTFS -NewFileSystemLabel $nombre -Confirm:0
"@
            Send-Command -Computername $cliente -Port 1655 -Command "$command" `
            -Verbose -Credential ($mycreds)
        Read-Host "VHD creado con éxito, presione ENTER para volver al menú"
 
          }
     "S" {Write-Host "Adiós!" -ForegroundColor Magenta
         Return
         }
     Default {Write-Warning "Por favor, introduzca una opción válida"
              sleep -milliseconds 2400}
    }
} While ($True)
Publicado el día 7 de enero de 2020

CATEGORÍAS

PowerShell, Red, Virtualización

ETIQUETAS

AsPlainText, clear, Clear-Host, ConvertTo-SecureString, Ejercicios de PowerShell, Enter-PSSession, Exit-PSSession, ExpandProperty, false, ForegroundColor, Format-Volume, Function, Get-NetIPAddress, Get-Random, Hyper-V, Invoke-Command, IP, IPAddress, IPv4, Jesús Niño, Jesús Niño Camazón, Length, Milliseconds, mount, Mount-VHD, New-NetIPAddress, New-Object, New-Partition, New-VHD, Parameter, Path, Read-Host, Remove, Remove-NetIPAddress, Screen, SecureString, Server, switch, System.Management.Automation.PSCredential, Virtual, Where-Object, WinRM, Write-Host

MÁS

  • Ejercicios de PowerShell: realizar operaciones en un equipo remoto
  • Instalación de servicios de configuración dinámica de sistemas (Servicios en red)
  • Ejercicios de seguridad: práctica sobre virus
  • Ejercicios de PowerShell: obtener información sobre los dispositivos de almacenamiento
  • Ejercicios de Routerboard de MikroTik: permitir y bloquear la conexión SSH en el Firewall de MikroTik
  • Ejercicios de PowerShell: crear mediante scripts una estructura de una red con un dominio y las configuraciones de GPOS que necesites