Using Powershell Variables HyperV Powershell Direct

Another new feature I love in Hyper-V 2016, like nested Virtualization, is Powershell Direct.  Powershell Direct allows you to connect to HyperV VMs directly through the Virtual Machine Bus. You use the same commands you normally use for Powershell remoting. Which are Invoke-Command and Enter-PSSession. To run these commands you need administrator credentials on the Hyper-V server. Which command lets you use variables in Variables HyperV Powershell Direct.

Each of these commands are useful, but only for certain commands and operations respectively. Lets consider an example. If we were configuring a new VM to be operational. Some of the things we might need to do include, joining the domain and setting an IP or DNS servers.


We want to use Enter-PSSession to run any configuration commands, like initializing disks, or other commands we don’t need to pass variables through the session for.

$remotecred = get-credential 
$domaincred = get-credential 
$vm = 'vm01'

enter-pssession -computername $vm -cred $remotecred

[vm01] PS C:\users\%username%>
get-disk | where {$_.IsOffline -eq $true} | initialize-disk


For this example $remotecred the credential with access to the Hyper-V VM Bus to access the VM. And $vm is our VM name. Once you enter the session the begging of your terminal will say [computername here] PS c:\ >


Invoke-command is what we want to use for anything that we’ve set a variable. We can easily and simply pass variables to the remote machine as follows:

$remotecred = get-credential
$domaincred = get-credential
$vm = 'vm01'

invoke-command -VMName $vm -credential $remotecred -scriptblock

{ add-computer –domainname -Credential $using:domaincred -restart –force}

In this quick example, everything is the same as above, except we added $domaincred which is the account authorized to join machines to the domain.  When you are in the script block this is executing on the remote machine, putting “$using:” before the variable calls the variable from your local powershell session.

I cannot recall what version of powershell this was introduced, but regardless get on Powershell 5.1 or start using Powershell Core 6.