PowerShell Direct - handling authentication for better scripting

In Windows 10 (and Windows Server 2016 TP2) we introduced a great new feature called PowerShell Direct.  You can read about it all here: https://blogs.technet.com/b/virtualization/archive/2015/05/14/powershell-direct-running-powershell-inside-a-virtual-machine-from-the-hyper-v-host.aspx

In essence it allows you to run PowerShell code in a virtual machine without having to configure networking / PowerShell remoting / etc...

This is a very powerful tool that I have been using a lot as we work on various features - so this week I am going to post a bunch of information on how you can use PowerShell Direct to do cool things in your environment.  In this post I am going to discuss the topic of authentication and PowerShell Direct.

PowerShell Direct requires that you are correctly authenticated with the guest operating system in order to run PowerShell commands inside the virtual machine.  However, there are four ways you can achieve this:

  1. The first and simplest way is to have the same user credentials be valid in the host and the guest.  
     
    1. This is quite easy if you are logging in with your Microsoft account - or if you are in a domain environment.  In this scenario you can just run "invoke-command -VMName "test" {get-process}" and party on.

       

  2. Let PowerShell Direct prompt you for credentials.
     
    1. If your credentials do not match - then you will automatically get a credential prompt allowing you to provide the appropriate credentials for the virtual machine.

       

  3. Store credentials in a variable for reuse.
     
    1. Running a simple command like this:

      $localCred = Get-Credential

      And then running something like this:

      invoke-command -VMName "test" -Credential $localCred {get-process} 

      Will mean that you only get prompted once for your credentials.

       

  4. Be grossly insecure and code your credentials into your scripts.
     
    1. Okay - before I go any further let me be really clear - this is a *bad thing to do* *do not do this in a production system* *do not do this with real passwords* .  That said - as someone who builds more system automation code than I care to think about - this is something I do all the time.  You can actually hand craft a PSCredential object with some code like this:

      $localCred = new-object -typename System.Management.Automation.PSCredential -argumentlist "Administrator", (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force)

      Grossly insecure - but handy (as these things often are).  Now you get no prompts at all. 

These are all the options for authentication with PowerShell Direct.

Cheers,
Ben