Public/Set-WindowsServerLabVM.ps1

Function Set-WindowsServerLabVM {   
    [cmdletbinding()]  
    Param(
        [parameter (Mandatory=$True)]
        [string]$Name,

        [Parameter (Mandatory=$True)]
        [PSCredential]$Credential,
    
        [string]$IPAddress,
    
        [byte]$SubnetBits,
    
        [string]$DefaultGateway,
    
        [string[]]$DNSServers,

        [string]$EthernetAdapterName='Ethernet',

        [int]$Attempts=1
    )
    try { 
        $ErrorActionPreference = 'stop'
        $Session = Wait-ForPSDirectSession -VMName $Name -Credential $Credential -Attempts $Attempts
        Invoke-Command -Session $Session -ScriptBlock {          
            $adapter = Get-NetAdapter -Name $Using:EthernetAdapterName
            New-NetIPAddress -InterfaceAlias $adapter.Name -AddressFamily IPv4 -IPAddress $Using:IPAddress -PrefixLength $Using:SubnetBits -DefaultGateway $Using:DefaultGateway | Out-Null         
            Set-DnsClientServerAddress -InterfaceAlias $adapter.Name -ServerAddresses $Using:DNSServers | Out-Null 
            Rename-Computer -ComputerName $env:COMPUTERNAME -NewName $Using:Name
        }
        try {
            Invoke-Command -Session $Session -ScriptBlock {
                Restart-Computer -Force
                Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue
            }
        }
        catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
            Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue
        }
    }
    catch {    
        $PSCmdlet.ThrowTerminatingError($_)
    }  
    finally {  
        Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue
    }            
}