Enter-HyperVVM
Hyper-V: Establishes a PowerShell Direct session with a virtual machine
#Requires -Version 5.1
#Requires -Modules Hyper-V
[CmdletBinding()]
Param (
[string]$ComputerName = "localhost",
[PSCredential]$Credential,
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
[PSCredential]$VMCredential,
[scriptblock]$ScriptBlock
)
Process {
try {
$params = @{
'ComputerName' = $ComputerName
'ErrorAction' = 'Stop'
}
if ($Credential) { $params.Add('Credential', $Credential) }
$vm = Get-VM @params | Where-Object { $_.Name -eq $Name -or $_.Id -eq $Name }
if (-not $vm) {
throw "Virtual machine '$Name' not found on '$ComputerName'."
}
if ($ScriptBlock) {
$result = Invoke-Command -VMName $vm.Name -Credential $VMCredential -ScriptBlock $ScriptBlock -ErrorAction Stop
Write-Output $result
}
else {
Enter-PSSession -VMName $vm.Name -Credential $VMCredential
}
}
catch {
throw
}
}Specifies the name of the Hyper-V host. Defaults to the local machine.
Specifies the credentials to use for the remote connection to the Hyper-V host.
Specifies the name or ID of the virtual machine.
Specifies the credentials to use inside the virtual machine.
Optional. A script block to execute inside the virtual machine. If not provided, an interactive session is attempted.