Budowa własnego laba: AD + klient na Hyper-V – kompletny przewodnik

PowerShell Budowa własnego Laba Active Directory
HOST (HYPER-V)
   ├── kontroler domeny (DC)
   └── stacja robocza (CLIENT)
# Sprawdzenie czy wirtualizacja jest włączona w BIOS
PS C:\Windows> Get-ComputerInfo | Select-Object HyperVisorPresent, HyperVRequirementVirtualizationFirmwareEnabled

HyperVisorPresent HyperVRequirementVirtualizationFirmwareEnabled
----------------- ----------------------------------------------
             True

# Instalacja roli Hyper-V
PS C:\Windows> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

Path          :
Online        : True
RestartNeeded : False

# Uwaga: Po wykonaniu tej komendy konieczny jest restart komputera.

PS C:\Windows> Restart-Computer -Force     
# Utworzenie nowego wirtualnego przełącznika sieciowego
PS C:\Windows> New-VMSwitch -Name "LabNet" -SwitchType Internal

Name   SwitchType NetAdapterInterfaceDescription
----   ---------- ------------------------------
LabNet Internal

# Nadanie nowego IP
PS C:\Windows> New-NetIPAddress -InterfaceAlias "vEthernet (LabNet)" -AddressFamily IPv4 -IPAddress "192.168.100.1" -PrefixLength 24

IPAddress         : 192.168.100.1
InterfaceIndex    : 67
InterfaceAlias    : vEthernet (LabNet)
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Tentative
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore

# Konfiguracja NAT (Network Address Translation) aby VM miały Internet
PS C:\Windows> New-NetNat -Name LabNat -InternalIPInterfaceAddressPrefix "192.168.100.0/24"

Name                             : LabNat
ExternalIPInterfaceAddressPrefix :
InternalIPInterfaceAddressPrefix : 192.168.100.0/24
IcmpQueryTimeout                 : 30
TcpEstablishedConnectionTimeout  : 1800
TcpTransientConnectionTimeout    : 120
TcpFilteringBehavior             : AddressDependentFiltering
UdpFilteringBehavior             : AddressDependentFiltering
UdpIdleSessionTimeout            : 120
UdpInboundRefresh                : False
Store                            : Local
Active                           : True
PowerShell - budowa własnego laba - konfiguracja sieci
# Konfiguracja ścieżek i zasobów
$VMPath = "C:\Hyper-V-Lab\VMs"
$ISOPathServer = "C:\Obrazy\WinSrv_2025.iso"         # <--- ZMIEN NA SWOJĄ ŚCIEŻKĘ
$ISOPathClient = "C:\Obrazy\Win11_25H2.iso"          # <--- ZMIEN NA SWOJĄ ŚCIEŻKĘ
$SwitchName = "LabNet"

# Sprawdzenie czy katalog dla laba istnieje, jeżeli nie to do tworzymy
if (!(Test-Path $VMPath)) {
    New-Item -Path $VMPath -ItemType Directory -Force
}

# Funkcja pomocnicza do tworzenia VM
function New-LabVM {
    param(
        [string]$VMName,           # Nazwa VM
        [int]$MemoryStartup,       # Pamięć RAM [MB]
        [string]$ISOPath,          # Ścieżka do pliku ISO z systemem
        [int]$VHDSizeGB            # Dysk [GB]
    )

    Write-Host "Tworzenie VM: $VMName..." -ForegroundColor Cyan

    # 1. Tworzenie dysku VHDx / Sprawdzamy czy katalog z nazwą VM istnieje, jeżeli nie to go tworzymy
    $VHDPath = "$VMPath\$VMName\$VMName.vhdx"
    if (!(Test-Path "$VMPath\$VMName")) { New-Item -Path "$VMPath\$VMName" -ItemType Directory -Force }

    New-VHD -Path $VHDPath -SizeBytes ($VHDSizeGB * 1GB) -Dynamic       # Tworzy nowy dysk dynamiczny

    # 2. Tworzenie maszyny wirtualnej (Generacja 2 dla UEFI)
    New-VM -Name $VMName `
           -MemoryStartupBytes ($MemoryStartup * 1MB) `
           -SwitchName $SwitchName `
           -Generation 2 `
           -VHDPath $VHDPath `
           -Path "$VMPath\$VMName"

    # 3. Podpięcie ISO (Instalator)
    Add-VMDvdDrive -VMName $VMName -Path $ISOPath

    # 4. Konfiguracja procesora (Wirtualizacja zagnieżdżona - przydatna do dalszych testów)
    Set-VMProcessor -VMName $VMName -ExposeVirtualizationExtensions $true

    # 5. Integracja (Guest Services) - pozwala na kopiowanie plików do VM
    Enable-VMIntegrationService -VMName $VMName -Name "Guest Service Interface"

    # 6. Konfiguracja liczby rdzeni procesora (Win 11 wymaga 2)
    Set-VMProcessor -VMName $VMName -Count 2
    
    # 7. konfiguracja Trusted Platfom
    # Tworzenie lokalnego key protectora
    $kp = New-HgsKeyProtector -Owner (Get-HgsGuardian) -AllowUntrustedRoot

    # Przypisanie key protectora do VM
    Set-VMKeyProtector -VMName $VMName -KeyProtector $kp.RawData

    # Włączenie vTPM
    Enable-VMTPM -VMName $VMName

    Write-Host "VM $VMName utworzona pomyślnie." -ForegroundColor Green
}
PS C:\WINDOWS\system32> New-LabVM -VMName "DC" -MemoryStartup 4096 -ISOPath $ISOPathServer -VHDSizeGB 60
Tworzenie VM: DC...


    Directory: C:\Hyper-V-Lab\VMs


Mode                 LastWriteTime         Length Name                                                                                                              
----                 -------------         ------ ----                                                                                                              
d-----        21/03/2026     15:55                DC                                                                                                              

ComputerName            : DELL
Path                    : C:\Hyper-V-Lab\VMs\DC01\DC01.vhdx
VhdFormat               : VHDX
VhdType                 : Dynamic
FileSize                : 4194304
Size                    : 64424509440
MinimumSize             : 
LogicalSectorSize       : 512
PhysicalSectorSize      : 4096
BlockSize               : 33554432
ParentPath              : 
DiskIdentifier          : D72155E7-5F89-46EB-8D96-81F8EE50279E
FragmentationPercentage : 0
Alignment               : 1
Attached                : False
DiskNumber              : 
IsPMEMCompatible        : False
AddressAbstractionType  : None
Number                  : 


Name             : DC
State            : Off
CpuUsage         : 0
MemoryAssigned   : 0
MemoryDemand     : 0
MemoryStatus     : 
Uptime           : 00:00:00
Status           : Operating normally
ReplicationState : Disabled
Generation       : 2

VM DC utworzona pomyślnie.
PS C:\WINDOWS\system32> New-LabVM -VMName "CLIENT" -MemoryStartup 4096 -ISOPath $ISOPathClient -VHDSizeGB 60
Tworzenie VM: CLIENT...


    Directory: C:\Hyper-V-Lab\VMs


Mode                 LastWriteTime         Length Name                                                                                                              
----                 -------------         ------ ----                                                                                                              
d-----        21/03/2026     15:57                CLIENT                                                                                                          

ComputerName            : DELL
Path                    : C:\Hyper-V-Lab\VMs\CLIENT01\CLIENT01.vhdx
VhdFormat               : VHDX
VhdType                 : Dynamic
FileSize                : 4194304
Size                    : 64424509440
MinimumSize             : 
LogicalSectorSize       : 512
PhysicalSectorSize      : 4096
BlockSize               : 33554432
ParentPath              : 
DiskIdentifier          : 363DC99C-3B95-431D-BEA7-0E3F8818EE9E
FragmentationPercentage : 0
Alignment               : 1
Attached                : False
DiskNumber              : 
IsPMEMCompatible        : False
AddressAbstractionType  : None
Number                  : 


Name             : CLIENT
State            : Off
CpuUsage         : 0
MemoryAssigned   : 0
MemoryDemand     : 0
MemoryStatus     : 
Uptime           : 00:00:00
Status           : Operating normally
ReplicationState : Disabled
Generation       : 2

VM CLIENT utworzona pomyślnie.
PowerShell - budowa własnego laba - Hyper-V
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows Server
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PowerShell - budowa własnego laba - Instalacja Windows 11
PS C:\Users\Administrator> Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
Ethernet                  Microsoft Hyper-V Network Adapter             4 Up           00-15-5D-C4-CB-1C        10 GbpsNey

PS C:\Users\Administrator> New-NetIPAddress -ifIndex 4 -IPAddress 192.168.100.10 -PrefixLength 24 -DefaultGateway 192.168.100.1


IPAddress         : 192.168.100.10
InterfaceIndex    : 4
InterfaceAlias    : Ethernet
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Tentative
ValidLifetime     :
PreferredLifetime :
SkipAsSource      : False
PolicyStore       : ActiveStore

PS C:\Users\Administrator> Set-DnsClientServerAddress -InterfaceIndex 4 -ServerAddresses 127.0.0.1
PS C:\Users\Administrator> ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : WIN-4LE5G635KC2
   Primary Dns Suffix  . . . . . . . :
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter
   Physical Address. . . . . . . . . : 00-15-5D-C4-CB-1C
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::cbb:123c:240:3a59%4(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.100.10(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.100.1
   DHCPv6 IAID . . . . . . . . . . . : 83891549
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-31-51-05-9D-00-15-5D-C4-CB-1C
   DNS Servers . . . . . . . . . . . : 127.0.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled
PS C:\Windows\system32> Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
Ethernet                  Microsoft Hyper-V Network Adapter            10 Up           00-15-5D-C4-CB-1E        10 Gbps

PS C:\Windows\system32> New-NetIPAddress -ifIndex 10 -IPAddress 192.168.100.20 -PrefixLength 24


IPAddress         : 192.168.100.20
InterfaceIndex    : 10
InterfaceAlias    : Ethernet
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Tentative
ValidLifetime     :
PreferredLifetime :
SkipAsSource      : False
PolicyStore       : ActiveStore

# Wskazujemy na DC jako serwer DNS (Kluczowe dla AD!)
PS C:\Windows\system32> Set-DnsClientServerAddress -InterfaceIndex 10 -ServerAddresses 192.168.100.10        
PS C:\Windows\system32> ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : DESKTOP-3FKIGH6
   Primary Dns Suffix  . . . . . . . :
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter
   Physical Address. . . . . . . . . : 00-15-5D-C4-CB-1E
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::2853:dcc5:3e7b:de66%10(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.100.20(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.100.1
   DHCPv6 IAID . . . . . . . . . . . : 83891549
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-31-51-B2-CE-00-15-5D-C4-CB-1E
   DNS Servers . . . . . . . . . . . : 192.168.100.10
   NetBIOS over Tcpip. . . . . . . . : Enabled
PS C:\Windows\system32> ping 192.168.100.10

Pinging 192.168.100.10 with 32 bytes of data:
Reply from 192.168.100.10: bytes=32 time<1ms TTL=128
Reply from 192.168.100.10: bytes=32 time<1ms TTL=128
Reply from 192.168.100.10: bytes=32 time<1ms TTL=128
Reply from 192.168.100.10: bytes=32 time=1ms TTL=128

Ping statistics for 192.168.100.10:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 1ms, Average = 0ms

PS C:\Windows\system32> Test-Connection -ComputerName 192.168.100.10 -Count 4

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
DESKTOP-3F... 192.168.100.10                                                            32       11
DESKTOP-3F... 192.168.100.10                                                            32       0
DESKTOP-3F... 192.168.100.10                                                            32       2
DESKTOP-3F... 192.168.100.10                                                            32       1
# Zmiana nazwy serwera
Rename-Computer -NewName DC -Restart

# Sprawdzenie nowej nazwy
PS C:\Users\Administrator> $env:Computername
DC
# 1. Instalacja roli AD DS oraz narzędzi zarządzania
PS C:\Users\Administrator> Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools

Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {Active Directory Domain Services, Group P...

# 2. Promocja serwera do Kontrolera Domeny (Nowy Las)
# Hasło trybu DSRM musi spełniać politykę złożoności (ważne!)
$SafeModePassword = Read-Host -AsSecureString

Install-ADDSForest `
    -InstallDns `
    -DomainName "lab.local" `
    -DomainNetbiosName "LAB" `
    -ForestMode "WinThreshold" `
    -DomainMode "WinThreshold" `
    -DatabasePath "C:\Windows\NTDS" `
    -SysvolPath "C:\Windows\SYSVOL" `
    -LogPath "C:\Windows\NTDS" `
    -SafeModeAdministratorPassword $SafeModePassword `
    -Force:$true

# Po tej komendzie serwer zrestartuje się automatycznie.
PowerShell - budowa własnego laba - log in AD
# 2. Dołączenie do domeny
# Wymaga podania poświadczeń administratora domeny
$DomainCred = Get-Credential -Message "Podaj dane Administratora domeny (LAB\Administrator)"

Add-Computer -DomainName "lab.local" -Credential $DomainCred -Restart

# Maszyna zrestartuje się automatycznie po pomyślnym dołączeniu.
PowerShell - budowa własnego laba - log in AD
# Tworzenie nowego użytkownika w AD
$Password = Read-Host -AsSecureString
New-ADUser -Name "Jan Kowalski" -GivenName "Jan" -Surname "Kowalski" -SamAccountName "jkowalski" -UserPrincipalName "jkowalski@lab.local" -AccountPassword $Password -Enabled $true -ChangePasswordAtLogon $false

# Dodanie użytkownika do grupy Domain Admins i Remote Desktop Users 
"Domain Admins", "Remote Desktop Users" | Add-ADGroupMember -Members jkowalski
# Tworzenie czystej migawki po konfiguracji
$VMNames = @("DC", "CLIENT")
$CheckpointName = "Clean_Install_Domain_Joined"

foreach ($VM in $VMNames) {
    Write-Host "Tworzenie migawki dla $VM..." -ForegroundColor Cyan
    Checkpoint-VM -Name $VM -SnapshotName $CheckpointName
}


# W celu sprawdzenia
PS C:\WINDOWS\system32> Get-VMSnapshot -VMName DC, CLIENT

VMName Name                                                    SnapshotType CreationTime        ParentSnapshotName                                     
------ ----                                                    ------------ ------------        ------------------                                     
DC     Automatic Checkpoint - DC - (21/03/2026 - 18:42:34)     Standard     21/03/2026 18:42:35                                                        
CLIENT Automatic Checkpoint - CLIENT - (22/03/2026 - 14:01:07) Standard     22/03/2026 14:01:08                                                        
DC     Clean_Install_Domain_Joined                             Standard     28/03/2026 11:42:43 Automatic Checkpoint - DC - (21/03/2026 - 18:42:34)    
CLIENT Clean_Install_Domain_Joined                             Standard     28/03/2026 11:42:43 Automatic Checkpoint - CLIENT - (22/03/2026 - 14:01:07)
Labs od demand - platforma do tworzenia środowisk labowych

To wszystko na dziś!

Jeśli masz ciekawe spostrzeżenia lub doświadczenia w tym temacie – koniecznie podziel się nimi w komentarzach.
A jeśli moje materiały są dla Ciebie pomocne, możesz postawić mi wirtualną kawę.

Dzięki za wsparcie!

Postaw mi kawę na buycoffee.to

Adam Pietrzak

Administrator | Trener i autor szkoleń | Entuzjasta PowerShella

Administrator systemów i sieci wsparcia działań wojskowych z ponad 10-letnim doświadczeniem. Praktyk w dziedzinie zarządzania Active Directory, bezpieczeństwa systemu Windows oraz automatyzacji zadań (PowerShell). Trener i twórca materiałów edukacyjnych (szkolenia, warsztaty, artykuły, podręczniki). Pasjonat dzielenia się wiedzą i wspierania początkujących administratorów IT. Prywatnie – amator aktywnego wypoczynku i rodzinnych podróży.


PowerShell - 10 sposobów na optymalizację codziennej pracy
Podziel się

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *