Tuesday, July 22, 2014

Copying files into Hyper-V VMs with Copy-VMFile

Over the life of Hyper-V there have been lots of convoluted ways that folks have used to get files in and out of Hyper-V VMs.

The most common method has been to mount the VHD and copy files in and out.  But you can't do this while the VM is running.

Then there the issue of using differencing disks or snapshots - and you want to replicate one file to many VMs.  Folks try and mount the parent virtual disk and copy files in - but due to the way that differencing disks work, this gives mixed results if it works at all.

Well, Hyper-V has a nifty feature of the Integration Components / Integration Services that allows you to inject files into a running VM.
The PowerShell cmdlet is Copy-VMFile.

I recently stumbled on this while getting some labs set up and I suddenly realized that I have 25 lab machines with 4 VMs each that my students will be using, and I have a broken lab if I don't correct one file.  Did I mention that I can't physically visit these servers?  I only have remote access.  What a pain.

Prior to being able to use the cmdlet you must have Guest Services enabled on your VM - and this is not on by default.

Enable-VMIntegrationService -Name 'Guest Service Interface' -VMName DSC01
Then, you can push a file into a VM from the Hyper-V Server by using -FileSource Host  And the Host is the only option.  You can only push in, not pullout.

Copy-VMFile -Name DSC01 -SourcePath .\1.2.0.0.zip -DestinationPath 'C:\Users\Public\1.2.0.0.zip' -FileSource Host -CreateFullPath
You use the -Force parameter if you are overwriting an existing file.  And you don't need -Force otherwise.
-CreateFullPath does just what you would think it does, it creates the folder path you defined if it is not already present.

Simple as that.

There is some safety built into this I will mention.  Such as you cannot copy into the system path and other permissions blocks you will encounter.

Hyper-V has always approached the VM from the angle that it is evil, the VM is malicious.  This is the protection assumption.  Always keep that machine contained.

3 comments:

Anonymous said...

Can you give an example command for pulling files out of a running VM?
I have only been able to copy files to a VM with powershell.

BrianEh said...

Thanks for trying.

Did you remove the "-FileSource Host"?

I honestly did not have the time to try it, but I now see that I need to. Give me a bit.

BrianEh said...

I finally checked on this and asked the product team about it.
It is a one way street. From the host to the VM only.

Hyper-V has always had the assumption that the VM is malicious when boundaries come up.

In this case you could extend that idea to secrets being taken from within a VM by a malicious admin.