Functions/LabVM/Enter-LabVMSession.ps1
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 |
#Requires -Version 5.0 function Enter-LabVMSession { [CmdletBinding(DefaultParameterSetName = 'MachineName')] param ( [Parameter(Mandatory = $true, ParameterSetName = 'Machine', ValueFromPipeline = $true)] [LabMachine]$Machine, [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'MachineName')] [string]$MachineName, [PSCredential]$Credential, [Parameter(Mandatory = $false)] [string]$NetworkAdapterName, [Parameter(Mandatory = $false)] [switch]$CredSSP ) if (-not (Test-Administrator)) { throw 'Please run this command as Administrator.' } if ($($PSCmdlet.ParameterSetName) -ne 'Machine') { if ($MachineName) { $Machine = Get-LabMachine -Name $MachineName } else { $Machine = Get-LabMachine } } if (-not $Machine) { return } if (-not $Credential) { $domainNetwork = $Machine.NetworkAdapters.Network | Where-Object { $_.Domain } | Select-Object -First 1 if ($domainNetwork) { $domain = $domainNetwork.Domain if ($domain.AdministratorPassword) { $Credential = New-Object -TypeName PSCredential -ArgumentList "$($domain.NetbiosName)\Administrator",$domain.AdministratorPassword } } if (-not $Credential) { $Credential = New-Object -TypeName PSCredential -ArgumentList "$($Machine.Name)\Administrator",$Machine.AdministratorPassword } } $vm = Get-VM | Where-Object { $_.Name -eq $Machine.Name } if (-not $vm) { throw "Lab-VM with name '$($Machine.Name)' not found" } if ($NetworkAdapterName) { $ipAddress = $vm ` | Get-VMNetworkAdapter ` | Select-Object -Property * -ExpandProperty IPAddresses ` | Where-Object { $_.Name -eq $NetworkAdapterName -and $_.Contains('.') } ` | Select-Object -First 1 } else { $ipAddress = $vm ` | Get-VMNetworkAdapter ` | Select-Object -Property * -ExpandProperty IPAddresses ` | Where-Object { $_.Contains('.') } ` | Select-Object -First 1 } if (-not $ipAddress) { throw "Unable to determine ip-address for Lab-VM with name '$($Machine.Name)'" } if ($CredSSP.IsPresent) { return Enter-PSSession -ComputerName $ipAddress -Credential $Credential -Authentication Credssp } else { return Enter-PSSession -ComputerName $ipAddress -Credential $Credential } } |