Public/Set-WindowsServerLabVM.ps1
Function Set-WindowsServerLabVM { [cmdletbinding()] Param( [Parameter (Mandatory = $True, ValueFromPipelineByPropertyName = $true)] [Alias('Name')] [string[]]$VMName, [Parameter (Mandatory = $True)] [PSCredential]$Credential, [Parameter (ParameterSetName = 'Network')] [string]$IPAddress, [Parameter (ParameterSetName = 'Network')] [byte]$SubnetBits, [Parameter (ParameterSetName = 'Network')] [string]$DefaultGateway, [Parameter (ParameterSetName = 'Network')] [string[]]$DNSServers, [Parameter (ParameterSetName = 'Network')] [string]$EthernetAdapterName, [int]$Attempts = 1 ) BEGIN { $networkConfigRequired = $false # network config taken care of by DHCP for target nodes if ($PSBoundParameters.ContainsKey('IPAddress')) { $networkConfigRequired = $true } } PROCESS { foreach ($v in $VMName) { try { $ErrorActionPreference = 'stop' $Session = Wait-ForPSDirectSession -VMName $v -Credential $Credential -Attempts $Attempts Invoke-Command -Session $Session -ScriptBlock { if ($Using:networkConfigRequired) { $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:v } 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 } } } } |