Design a site like this with WordPress.com
Get started

REVISE: Hyper-V Resource Control and Resource Metering

Very impressive links on Hyper-V Resource Control and Resource Metering.

Question: Windows Server 2012 and 2012 R2

IT organizations need tools to charge back business units that they support while providing the business units with the right amount of resources to match their needs. For hosting providers, it is equally important to issue chargebacks based on the amount of usage by each customer.

To implement advanced billing strategies that measure both the assigned capacity of a resource and its actual usage, earlier versions of Hyper-V required users to develop their own chargeback solutions that polled and aggregated performance counters. These solutions could be expensive to develop and sometimes led to loss of historical data.

To assist with more accurate, streamlined chargebacks while protecting historical information, Hyper-V in Windows Server 2012 introduces Resource Metering, a feature that allows customers to create cost-effective, usage-based billing solutions. With this feature, service providers can choose the best billing strategy for their business model, and independent software vendors can develop more reliable, end-to-end chargeback solutions on top of Hyper-V.

Key benefits

Hyper-V Resource Metering in Windows Server 2012 allows organizations to avoid the expense and complexity associated with building in-house metering solutions to track usage within specific business units. It enables hosting providers to quickly and cost-efficiently create a more advanced, reliable, usage-based billing solution that adjusts to the provider’s business model and strategy.

Use of network metering port ACLs

Enterprises pay for the Internet traffic in and out of their data centers, but not for the network traffic within their data centers. For this reason, providers generally consider Internet and intranet traffic separately for the purposes of billing. To differentiate between Internet and intranet traffic, providers can measure incoming and outgoing network traffic for any IP address range, by using network metering port ACLs.

Virtual machine metrics

Windows Server 2012 provides two options for administrators to obtain historical data on a client’s use of virtual machine resources: Hyper-V cmdlets in Windows PowerShell and the new APIs in the Virtualization WMI provider. These tools expose the metrics for the following resources used by a virtual machine during a specific period of time:

  • Average CPU usage, measured in megahertz over a period of time.
  • Average physical memory usage, measured in megabytes.
  • Minimum memory usage (lowest amount of physical memory).
  • Maximum memory usage (highest amount of physical memory).
  • Maximum amount of disk space allocated to a virtual machine.
  • Total incoming network traffic, measured in megabytes, for a virtual network adapter.
  • Total outgoing network traffic, measured in megabytes, for a virtual network adapter.

Movement of virtual machines between Hyper-V hosts—for example, through live, offline, or storage migrations—does not affect the collected data.

Question: Introduction to Resource Metering

Hi, I’m Lalithra Fernando, a program manager on the Hyper-V team, working in various areas including clustering and authorization, as well as with our Hyper-V MVPs. In this post, I’ll be talking about resource metering, a new feature in Hyper-V in Windows Server 2012.

As you’ve probably heard by now, Windows Server 2012 is a great platform for the private cloud. When we began planning this release, we realized that one of the things you need in order to run a cloud is to be able to charge your users for the resources they use.

This is the need resource metering fills. It allows you to measure the resource utilization of your virtual machines. You can use this information as a platform for your own dynamic chargeback solutions, where you can charge customers based on the resources they use instead of a flat upfront cost, or to plan your hosting capacity appropriately.

There are four resources that you can measure: your CPU, memory, network, and storage utilization. We measure these resources over the period of time between when you measure and when you last reset metering.

CPU (MHz): We report the average utilization in megahertz.

Now, you’re probably wondering why we don’t report this as a percentage. After all, that’s what we do in Hyper-V Manager. Well, we know that you like to move your virtual machines. With Windows Server 2012, you can live migrate your virtual machines all over the place. Naturally, the record of how much resources your virtual machine has used moves with it.

We want the virtual machine’s CPU utilization to make sense across multiple machines. If we report a percentage and you move the virtual machine to a host with different processing capabilities, it’s no longer clear what the percentage refers to.

Instead, we report in megahertz. For example, if your virtual machine had an average CPU utilization of 50% over the past billing cycle on a host with a CPU running at 3GHz, we would report 1500MHz.

If your virtual machine spent one hour on a host with a 3GHz CPU and used 50% and another hour on a host with 1GHz CPU and used 75%, we would report the following:

(3GHz * 1000MHz/1GHz * .5 * 1hr) + (1GHz * 1000MHz/1GHz * .75 * 1hr) = 2250MHz-Hr

Here I am converting the CPU capacity from GHz to MHz and figuring out how much of that capacity was used over each hour.

2250MHz-Hr / 2 Hours = 1125 MHz.

Then, I simply divide over the two hours to get this value.

One final note: we don’t report minimum and maximum utilization values for CPU. If you think on it a moment, you’ll come to the same realization we did: it is very likely that the minimum will be 0 and the maximum will be the full capacity of the hosts’ CPU at some point over the timespan you’re measuring. Since that’s not very useful, we don’t report it.

Memory (MB): We report the average, maximum, and minimum utilization here, in megabytes.

The minimum memory utilization captures the least memory used over the timespan measured. Since it’s not very useful to know that the minimum memory usage was zero if the virtual machine was ever turned off, we only look at the minimum memory utilization when the virtual machine is running.

We do include the offline time of the virtual machine when calculating the average memory utilization. This provides an accurate view of how much memory the virtual machine was using over that billing cycle, so that you can charge your users accurately.

Network (MB): We report network utilization in megabytes. Of course, we want this metric to be useful, so we considered how you would want to see this information broken down. One way you might want to distinguish between network traffic is to see how much traffic is inbound to the virtual machine, and how much is outbound.

The most important breakdown you will want is how much traffic does the virtual machine send or receive from the internet, which costs you money, and how much is just communication between virtual machines you host, which costs you nothing since it is just using your intranet. With this breakdown, you can charge your user accurately for their internet usage.

So how do we provide these breakdowns? We use ACLs set on the virtual machine’s network adapter. Each ACL has

  • Direction
    • “Inbound” or “Outbound”
  • Remote IP Address
    • The source or destination of the network packet, depending on direction
    • For example, 10.0.0.0/8
  • Action
    • Allow, Deny, or Meter

These ACLs are used for more than just resource metering; note the Allow and Deny actions. For our purposes, you set the action to “Meter”.

Enabling resource metering creates two sets of default metering ACLs, provided none are already configured. The first set of ACLs, one inbound and one outbound, has a remote IP address of *.*; this wildcard notation indicates that it will meter all IPv4 traffic that is not covered by another ACL. The second set has an IP address of *:*, which meters all IPv6 traffic.

With these metering ACLs, you can measure the total network traffic sent and received by the virtual machine, in megabytes. You can configure your own ACLs to count intranet traffic separately from internet traffic, and charge accordingly.

Disk (MB): As we spoke with customers, we realized that for chargeback purposes, they were only interested in the total disk allocation for a virtual machine. So, here we report that in megabytes.

The total value is the capacity (not the current size on disk) of the VHDs attached to the virtual machine plus the size of the snapshots. Take the following examples:

Fixed size disk: 

VM with a single 100GB fixed size VHDs attached

————————————————————-

Total Disk Allocation reported: 100GB

Dynamic disk:

VM with a single dynamic VHD attached, 

Current size 30GB, maximum size 100GB

————————————————————-

Total Disk Allocation reported: 100GB

With snapshots:

VM with a single dynamic size VHDs attached,

Current size 30GB, maximum size 100GB,

Plus a 20GB snapshot

————————————————————-

Total Disk Allocation reported: 120GB

Pass-through disks, DAS disks, guest iSCSI connections, and virtual Fibre Channel disks are not included in the total disk allocation metric.

Once you enable resource metering, Hyper-V will begin collecting data. You can reset metering at any time. We will then discard the data we have collected up to that point and start fresh. So, you will typically measure the utilization first, and then reset. When you measure, you are measuring the utilization over the timespan since you last reset metering. Metering is designed to collect this data over long periods of time. If you need greater granularity, you can look at performance counters. 

Having resource metering enabled and just capturing utilization data per your billing cycle has no noticeable performance impact. There will be some negligible disk and CPU activity as data is written to the configuration file.

You can try this all out for yourself now, with Windows Server 2012. In the next part, we’ll talk about how to actually use resource metering with our PowerShell cmdlets.

We hope this is useful for you. Please let us know how you’re using it! Thanks!

Question: Configuring Hyper-V Resource Metering

Windows Server 2012 Hyper-V contains a resource metering mechanism that makes it possible to track system resource usage either for a virtual machine or for a collection of virtual machines. Doing so can help you to keep track of the resources consumed by virtual machine collections. This information could be used to facilitate chargebacks (although Hyper-V does not contain a native chargeback mechanism).

Resource metering is not enabled by default. You can enable resource metering through PowerShell by entering the following command:

Get-VM <virtual machine name> |  Enable-VMResourceMetering

By default, Hyper-V collects resource metering statistics once every hour. You can change the collection frequency, but it is a good idea to avoid collecting metering data too frequently because doing so can impact performance and generate an excessive amount of metering data. If you want to change the collection frequency you can do so by using this command:

Set-VMHost –ComputerName <host server name>  -ResourceMeteringSaveInterval <HH:MM:SS>

As you look at the command above, you will notice that the collection frequency is being set at the host server level. You cannot adjust the frequency on a per VM basis. You can see what this command looks like in figure 1.

[Click on image for larger view.]Figure 1. You can change the resource metering collection frequency.

When you enable resource metering, there are a number of different resource usage statistics that are compiled. These statistics include:

  • The average CPU usage (measured in MHz)
  • The average physical memory usage (measured in MB)
  • The minimum memory usage (measured in MB)
  • The maximum memory usage (measured in MB)
  • The maximum amount of disk space allocated to a VM
  • The total inbound network traffic (measured in MB)
  • The total outbound network traffic (measured in MB)

The easiest way to view a virtual machine’s resource usage is to enter the following command:

Get-VM <virtual machine name> | Measure-VM

This command will display all of the available metering data for the virtual machine that you have specified.

Similarly, resource metering data can be displayed for all of the virtual machines that are running on the host server. If you want to see monitoring data for all of the virtual machines, you can acquire it by running this command:

Get_VM | Measure-VM

You can see what the output looks like in figure 2.

[Click on image for larger view.]Figure 2. This is what the resource metering output looks like.

Often times administrators are interested in specific aspects of resource consumption. For example, if a particular host server had limited network bandwidth available then an administrator would probably be interested in seeing the amount of network traffic that each virtual machine was sending and receiving. Conversely, if that same server had far more processing power than what would ever be needed by the virtual machines that are running on it, then the administrator probably would not need to monitor the average CPU usage.

Although you cannot turn data collection on or off for individual statistics, you can configure PowerShell to display only the statistics that you are interested in. The key to doing so is to know the object names that PowerShell assigns to each statistic. You can see the object names by entering the following command:

Get-VM | Measure-VM | Select-Object *

The column on the left side of the output lists the names that PowerShell uses for the individual statistics. You can see what this looks like in figure 3.

[Click on image for larger view.]Figure 3. You can get the object names from the column on the left.

There are a couple of things that you might have noticed in the figure above. First, there are more objects than what are displayed by default. Second, there are more objects than what I listed earlier. The reason for this is that these screen captures came from a server running Windows Server 2012 R2 Preview. Microsoft is extending the Resource Metering feature in Hyper-V 2012 R2 to include additional metering objects. In this article however, I only listed the objects that are available today.

With that in mind, let’s suppose that you only wanted to list the maximum memory consumption for each VM. You could do so by using this command:

Get-VM | Measure-VM | Select-Object VMName, MaxRAM

You can see the output in figure 4. Keep in mind that you can adapt this command to display any combination of objects that you want.

[Click on image for larger view.]Figure 4. PowerShell can display specific resource metering data.

As you can see, resource metering is useful for tracking resource consumption. It can also be useful for performing chargebacks, although there is no native Hyper-V chargeback mechanism.

Question: Resource Metering in Hyper-V

Why is Hyper-V Resource Metering Important?

The American National Institute of Standards and Technology gives us one of the best definitions of a cloud in their Special Publication 800-145, entitled “The NIST Definition of Cloud Computing.” In this document they describe a cloud as having five essential characteristics. One of the traits that they describe as being necessary to have a cloud is a measured service:

Cloud systems automatically control and optimize resource use by leveraging a metering capability at some level of abstraction appropriate to the type of service (e.g., storage, processing, bandwidth, and active user accounts). Resource usage can be monitored, controlled, and reported, providing transparency for both the provider and consumer of the utilized service.

What does this mean? A cloud enables a tenant to consume just what they need and pay for what they use. The cloud must be able to measure that usage. Using this information, a cloud vendor can charge the tenant for their resource usage.

Hyper-V resource metering

Resource metering is an important part of any Hyper-V deployment. (Image: Dreamstime)

That’s fine for a hosting company. What about in a private cloud, that is, an infrastructure that runs on premise? Traditionally the IT department is run as a cost center, or as the board of directors unfortunately see it, as a budgetary black hole. IT can change this incorrect perception in one of two ways:

  • Cross-charging: Every department that consumes IT services and resources will be given their own IT budget to spend with the IT department. IT will provide those services and resources, and invoice their internal customers on a regular basis in a non-profit manner. This changes IT into a service organization.
  • Show-back reporting: Many organizations will never consider changing IT into a chargeable service. However, IT can show the business leaders the cost of providing services to each of the business groups by reporting usage and translating that usage into a monetary value. This is a company politics move that can change the perception of IT within the business.

In my opinion, these sorts of actions could misfire and lead to talk of out-sourcing and off-shoring, so be careful!

What Information is Collected?

Resource metering will collect the following data for each enabled virtual machine:

  • Average CPU usage in MHz
  • Average physical memory usage
  • Minimum physical memory usage
  • Maximum memory usage
  • Maximum physical amount of disk
  • Total incoming network traffic
  • Total outgoing network traffic

Note that in the case of dynamic virtual hard disks, the potential size, not the actual size, is reported for maximum physical amount of disk. Also note that all data is stored with the virtual machine and moves with the virtual machine as it migrates between hosts.

Enabling and Using Hyper-V Resource Metering

Resource metering is made available using PowerShell. You can write scripts using PowerShell or you can use other tools to leverage the functionality.

You must first enable metering on a per-virtual machine basis. The following snippet will enable metering on all virtual machines on a host:

PowerShell

1Get-VM -ComputerName Demo-Host2 | Enable-VMResourceMetering

Tip: Remember to enable metering on any virtual machine created afterwards because the above cmdlet will only affect existing virtual machines.

By default, resource metering will collect metrics every hour. This is based on a per-host setting called ResourceMeteringSaveInterval. You might want to change this setting to match your billing rate in a cloud. If you are just testing resource metering, then you might want a more frequent collection. This example will change the setting to every 10 seconds:

PowerShell

1Set-VMHost –ComputerName Demo-Host2 –ResourceMeteringSaveInterval 00:00:10

After the resource metering interval has passed, you will want to collect some metrics. Here’s a quick way to see all collected data:

PowerShell

1Get-VM -ComputerName Demo-Host2 | Measure-VM
Resource Metering tracks several different metrics for Hyper-V virtual machines

Measuring resource usage by Hyper-V virtual machines. (Image: Aidan Finn)

You could do something more targeted:

PowerShell

1Measure-VM -ComputerName Demo-Host2 -Name VM01

You can get a breakdown of bandwidth usage using:

PowerShell

1(Measure-VM -ComputerName Demo-Host2 -Name VM01).NetworkMeteredTrafficReport

Armed with this information, it won’t take you too long to find resource hogs on your hosts:

PowerShell

1Get-VM -ComputerName Demo-Host2 | Measure-VM | Sort-Object -Property AverageProcessorUsage -Descending | Select-Object -First 3 –Property VMName,AverageProcessorUsage
Identify top offenders on your Hyper-V hosts using Resource Metering

Reporting on the top resource consumers. (Image: Aidan Finn)

Resource metering is a tool that can show the value of IT to the business or enable a service provider to earn revenue. And with this data, you even have some ability to track usage for diagnostics reasons.

Question: HOW TO USE RESOURCE METERING IN HYPERV

IT Professionals need tools to track usage from specific business units. If you search you can find lot of monitoring tolls that can do this job but most of them need to pay and for free open source need an advance knowledge to install, configure and enable measure metrics for the resources that you want. 

I don’t want to say don’t use Monitoring Tool in your enviroment. But it takes times and need people to do this. If you are alone you need a quick solution until decide your Monitoring Solution in your enviroment. 

So today in this article i will show you another feature that was introduced in Windows Server 2012 Hyper-V that isn’t immediately obvious and is driven by using Windows PowerShell. I will explain only basic commands that can use it every day to measure metrics of your VM’S. The feature is amazing and it’s sure that i will come back with more advance commands of Resource Metering.

Resource Metering  expose the metrics for the following resources used by a virtual machine during a specific period of time:

  • Average CPU usage, measured in megahertz over a period of time.
  • Average physical memory usage, measured in megabytes.
  • Minimum memory usage (lowest amount of physical memory).
  • Maximum memory usage (highest amount of physical memory).
  • Maximum amount of disk space allocated to a virtual machine.
  • Total incoming network traffic, measured in megabytes, for a virtual network adapter.
  • Total outgoing network traffic, measured in megabytes, for a virtual network adapter.

 Let’s start to explain with practise.

  • As usuall open a Powershell as Administrator always.
  • First we must enable Resource Metering in VM. So Type
    Enable-VMResourceMetering –VMName WIN2012X64

  • If you want to verify that Resource Metering is enable in the VM TYPE
    Get-VM –VMName WIN2012X64| Format-Table Name, ResourceMeteringEnabled

  • Let’s see the resource metrics that we get from the VM
    Measure-VM –VMName WIN2012X64

  • Let’s see more details for the VM.
    Measure-VM –VMName WIN2012X64 | Format-List

  • If you want to measure network traffic 
    (Measure-VM –VMName WIN2012X64).NetworkMeteredTrafficReport

This is my last article for the 2015. I will come back with new Articles and Tutorials in 2016.

Merry Christmas and a Happy New Year!!!!!

Question: WINDOWS SERVER 2012 HYPER-V: VM RESOURCE METERING VIA POWERSHELL

With Windows Server 2012 Hyper-V Microsoft introduced a new feature in Hyper-V called Resource Metering which allows you to measure the usage of a virtual machine. This allows you to track CPU, Memory, Disk and network usage. This is a great feature especially if you need to do charge back or maybe even for trouble shooting.

Last week I had the chance to test and implement this feature for a customer.

First you can check the available PowerShell cmdlets for Hyper-V or for the the commands which include VMResourceMetering.

123Get-Command -Module Hyper-V Get-Command *VMResourceMetering*
Get-Command VMResourceMetering

The resource metering has to be enabled per Virtual Machine. This is great, so even if you move the virtual machine from one Hyper-V host to another you still have the usage data.

To enable the resource metering you can use the following cmdlet. In my case I enable VM Resource Metering for my VM called SQL2012.

1Get-VM SQL2012 | Enable-VMResourceMetering
Enable-VMResourceMetering

With the cmdlet Measure-VM you can get the statistic for the VM.

123Measure-VM -VMName SQL2012 Get-VM SQL2012 | Measure-VM | select *
Measure-VM

To get the network traffic use the properties of the NetworkMeteredTrafficReport.

1(Measure-VM -VMName SQL2012).NetworkMeteredTrafficReport
Measure-VM NetworkMeteredTrafficReport

Here is another great thing, if you want to measure Network from or to a specific network you can use VM Network Adapter ACLs to do so. With ACLs you can not just allow or deny network traffic, you can also meter network traffic for a special subnet or IP address.

1Add-VMNetworkAdapterAcl -VMName SQL2012 -Action Meter -RemoteIPAddress 10.10.0.0/16 -Direction Outbound
add-vmnetworkadapteracl measure-vm

Of course you can reset the statistics for the VM.

1Get-VM SQL2012 | Reset-VMResourceMetering
reset-vmresourcemetering

And to disable resource metering for the VM use:

1Get-VM SQL2012 | Disable-VMResourceMetering

I think this is one of the great new features of Windows Server 2012 Hyper-V which gets not a lot of attention but is really important.

REVISE: Time Synchronization in Windows Hyper-V

Below links give a detailed clarification on how time clock of guest operating systems in windows hyper-v works and how to solve its associated problems.

Question: Time Synchronization in Hyper-V

There is a lot of confusion about how time synchronization works in Hyper-V – so I wanted to take the time to sit down and write up all the details. 

There are actually multiple problems that exist around keeping time inside of virtual machines – and Hyper-V tackles these problems in different ways.

Problem #1 – Running virtual machines lose track of time.

While all computers contain a hardware clock (called the RTC – or real-time clock) most operating systems do not rely on this clock.  Instead they read the time from this clock once (when they boot) and then they use their own internal routines to calculate how much time has passed.

The problem is that these internal routines make assumptions about how the underlying hardware behaves (how frequently interrupts are delivered, etc…) and these assumptions do not account for the fact that things are different inside a virtual machine.  The fact that multiple virtual machines need to be scheduled to run on the same physical hardware invariably results in minor differences in these underlying systems.  The net result of this is that time appears to drift inside of virtual machines.

UPDATE 11/22: One thing that you should be aware of here: the rate at which the time in a virtual machine drifts is affected by the total system load of the Hyper-V server.  More virtual machines doing more stuff means time drifts faster.

In order to deal with time drift in a virtual machine – you need to have some process that regularly gets the real time from a trusted source and updates the time in a virtual machine.

Hyper-V provides the time synchronization integration services to do this for you.  The way it does this is by getting time readings from the management operating system and sending them over to the guest operating system.  Once inside the guest operating system – these time readings are then delivered to the Windows time keeping infrastructure in the form of an Windows time provider (you can read more about this here: http://msdn.microsoft.com/en-us/library/bb608215.aspx).   These time samples are correctly adjusted for any time zone difference between the management operating system and the guest operating system.

Problem #2 – Saved virtual machines / snapshots have the wrong time when they are restored.

When we restore a virtual machines from a saved state or from a snapshot we put back together the memory and run state of the guest operating system to exactly match what it was when the saved state / snapshot was taken.  This includes the time calculated by the guest operating system.  So if the snapshot was taken one month ago – the time and date will report that it is still one month ago.

Interestingly enough, at this point in time we will be reporting the correct (with some caveats) time in the systems RTC.  But unfortunately the guest operating system has no idea that anything significant has happened – so it does not know to go and check the RTC and instead continues with its own internally calculated time.

To deal with this the Hyper-V time synchronization integration service detects whenever it has come back from a saved state or snapshot, and corrects the time.  It does this by issuing a time change request through the normal user mode interfaces provided by Windows.  The effect of this is that it looks just like the user sat down and changed the time manually.  This method also correctly adjusts for time zone differences between the management operating system and the guest operating system.

Problem #3 – There is no correct “RTC value” when a virtual machine is started

As I have mentioned – physical computers have a RTC that operating systems look at when they first boot to get the time.  This real-time clock is backed by a small battery (you have probably seen the battery yourself if you have ever pulled apart a computer).  Unfortunately virtual machines do not have any “batteries”.  When a virtual machine is turned off there is no component that keeps track of time for it.  Instead – whenever you start a virtual machine we take the time from the management operating system and put this into the real-time clock of the virtual machine.

This is done without the use of the Hyper-V time synchronization integration servers (it happens long before the integration services have loaded). 

The downside of this approach is that this does not take into account any potential time zone differences between the management operating system and the guest operating system.  The reason for this is that “time zones” are a construct of the software that runs in a virtual machine – and is not communicated to the virtual hardware in any way.  So – in short – when we start a virtual machine there is no way for us to know what time zone the guest operating system believes it is in.

One partial mitigation we have for this issue is that when the Hyper-V time synchronization component loads for the first time – it does an initial user mode set of the time to ensure that the time gets corrected as quickly as possible (using the same technique as discussed in problem #2).

So now that you understand how this all works – let’s discuss some common issues and questions around virtual machines and time synchronization.

Question #1 – I have a virtual machine that is configured for a different time zone to the management operating system.  Should I disable the time synchronization component of Hyper-V?

No, no, no, no, no, no, no.  And I say again – no.  As I have mentioned above – all time synchronization that is done by the Hyper-V time synchronization integration service is time zone aware.  If you disable the Hyper-V time synchronization integration service you will disable all the time synchronization aspects of Hyper-V that are time zone aware – and only leave the initial RTC synchronization active – which is not time zone aware.

This means that your virtual machines will go from booting in the wrong time zone, and then being corrected as soon as the Hyper-V time synchronization integration service loads to booting in the wrong time zone and staying in the wrong time zone.

Question #2 – Is there any way that I can stop Hyper-V from putting the wrong time in the RTC at boot?

In short; no.  We need to put something in there – and that is the best thing that we have to work with.

Question #3 – Can’t you use UTC time in the RTC so that the correct time is established when the virtual machine boots?

UTC (which is the computer techy version of saying GMT) time would solve this problem nicely with only one problem.  Windows does not support UTC time in the BIOS (Linux does).  So while this would solve the problem for our Linux running user base – the fact of the matter is that most of our users run Windows – and this would not work for them.

Question #4 – What about if I am using a different time synchronization source (e.g. domain time or a remote time server)?

Hyper-V time synchronization was designed to “get along well” with other time synchronization sources.  You should not need to disable Hyper-V time synchronization in order to use a different time synchronization source – as long as it goes through the Windows time synchronization infrastructure.

In fact – if you are running a Domain Controller inside a virtual machine I would recommend that you leave Hyper-V time synchronization enabled but that you also setup an external time source.  You can do this by going to this KB article: http://support.microsoft.com/kb/816042and following the steps outlined in the “Configuring the Windows Time service to use an external time source” section.

UPDATE 11/22: I should have mentioned: since virtual machines tend to lose time much faster than physical computer, you need to configure any external time source to be checked frequently.  Once every 15 minutes is a good place to start.

Question #5 – How can I check what time source is being used by Windows inside of a virtual machine?

This is easy to do.  Just open an administrative command prompt and run “w32tm /query /source”.  If you are synchronizing with a remote computer – its name should be listed.  If you are using the Hyper-V time synchronization integration service you should see the following output:

image

If you see this output:

image

It means that there is no time synchronization going on for this virtual machine.  This is a very bad thing – as time will drift inside of the virtual machine.

Question #6 – Wait a minute!  My virtual machine should be synchronizing to the domain (or an external server) – but when I run that command it tells me that the Hyper-V time synchronization provider is being used!  How do I fix this!

I do not know why this happens – but sometimes it happens.  The first thing that you should do is to check that your domain does have a correctly configured authoritative time source.  There have been a small number of times when I have seen this problem being caused by the lack of an authoritative time source.

Alternatively – you can “partially disable” Hyper-V time synchronization.  The reason why I say “partially disable” is that you do not want to turn off the aspects of Hyper-V time synchronization that fix the time after a virtual machine has booted for the first time, or after the virtual machine comes back from a saved state.  No other time synchronization source can address these scenarios elegantly.

Luckily – there is a way to leave this functionality intact but still ensure that the day to day time synchronization is conducted by an external time source.  The key thing trick here is that it is possible to disable the Hyper-V time synchronization provider in the Windows time synchronization infrastructure – while still leaving the service running and enabled under Hyper-V.

To do this you will need to log into the virtual machine, open an administrative command prompt and run the following commands:

reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\VMICTimeProvider /v Enabled /t reg_dword /d 0

This command stops W32Time from using the Hyper-V time synchronization integration service for moment-to-moment synchronization.  Remember from earlier in this post that we do not go through the Windows time synchronization infrastructure to correct the time in the event of virtual machine boot / restore from saved state or snapshot.  So those operations are unaffected.

w32tm /config /syncfromflags:DOMHIER /update

This command tells Windows to go and look for the best time source in the domain hierarchy.  If you want to use an external time server instead you can use the commands found here: http://technet.microsoft.com/en-us/library/cc784553(WS.10).aspx

net stop w32time & net start w32time

w32tm /resync /force

These two commands just “kick the Windows time service” to make sure the settings changes take effect immediately.

w32tm /query /source

This final command should confirm that everything is working as expected.

When you run these commands you should see something like this:

image

Question #7 – I have a virtual machine that has gotten ahead of time, and it never gets corrected back to the correct time.  What is going on here?

As a general rule of thumb, when time drifts inside a virtual machine it runs slower than in the real world, and the time falls behind.  We will always detect and correct this.

However, in the past, we have had reports of software problems caused when the Hyper-V time synchronization integration service decides to adjust the time back – because it believes the virtual machine is ahead of time.  To deal with this (rare) issue – we put logic in our integration service that will not change the time if the virtual machine is more than 5 seconds ahead of the physical computer.

UPDATE 11/22: I was asked how having the virtual machine in a different time zone to the Hyper-V server would affect this.  The short answer is that it does not.  The 5 second check is done after we have done the necessary time zone translation.

Question #8 – When should I disable the Hyper-V time synchronization service (either in the virtual machine settings, or inside the guest operating system)?

Never.

There are definitely times when you will want to augment the functionality of the Hyper-V time integration services with a remote time source (be it a domain source or an external time server) but the only way to get the best experience around virtual machine boot / restore operations is to leave the Hyper-V time integration services enabled.

Question: Hyper-V, CPU Load and System Clock Drift

Using Hyper-V Server, you may find that the time is drifting a lot from the actual time, especially when Guest Virtual Machines are using CPUs heavily. The host OS is also virtualized, which means that the load of the host is also making the clock drift.

How to prevent the clock from drifting

  1. Disable the Time Synchronization in the Integration Services. (Warning, this setting is defined per snapshot)
  2. Import the following registry file : 

    Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\W32Time\Config] 
    “MaxAllowedPhaseOffset”=dword:00000001 
    “SpecialPollInterval”=dword:00000005 
    “SpecialInterval”=dword:00000001
    Note: If you are using notepad, make sure to save the file using an Unicode encoding.
  3. If the guest OS (and the server OS) is not on a domain, type in the following to set the time source : 

    w32tm /config /manualpeerlist:”time.windows.com,0x01 1.ca.pool.ntp.org,0x012.ca.pool.ntp.org,0x01″ /syncfromflags:MANUAL /update Note: Hosts FQDN are separated by spaces. 
  4. Run the following command to force a time synchronization 

    w32tm /resync
  5. Check that the clock is not drifting anymore by using this command : 

    w32tm /monitor /computer:time.windows.com

A bit of background …

The system I’m currently working on is heavily based on time. It relies a lot on timestamps taken from various steps of the process. If for some reason the system clock is unstable, that means the data generated by the system is unreliable. It sometimes generates corrupt data, and this is not good for the business.

I was investigating a sequence of events stored in the database in order that could not have happened, because the code cannot generate it this way.

After loads of investigation looking for code issues, I stumbled upon something rather odd in my application logs, considering that each line from the same thread should be time stamped later than the previous :

2009-10-13T17:15:26.541T [INFO][][7] … 
2009-10-13T17:15:26.556T [INFO][][7] … 
2009-10-13T17:15:24.203T [INFO][][7] … 
2009-10-13T17:15:24.219T [INFO][][7] … 
2009-10-13T17:15:24.234T [INFO][][7] …

All the lines above were generated from the same thread, which means that the system time changed radically between the second and the third line. From the application point of view, the time went backward of about two seconds and that also means that during that two seconds, there were data generated in the future. This is not very good…

The Investigation

Looking at the Log4net source code, I confirmed that the time is grabbed using System.DateTime.Now call, which excludes any code issues.

Then I looked at the Windows Time Service utility, and by running the following command :

w32tm /stripchart /computer:time.windows.com

I found out that the time difference from the NTP source was very different, something like 10 seconds. But the most disturbing was not the time difference itself, but the evolution of that time difference.

Depending on the load of the virtual machine, the difference would grow very large, up to a second behind in less than a minute. Both the host and the guest machines were exposing this behavior. Since Hyper-V Integration Services are by default synchronizing the clock of all the virtual machines on the guest OS, that means that the load of a single virtual machine can influence the clock of all other virtual machines. The host machine CPU load can also influence the overall clock rate, because it is also virtualized.

Trying to explain this behavior

To try and make an educated guess, the time source used by windows seems to be the TSC of the processor (by the use of the RDTSC opcode), which is virtualized. The preemption of the CPU by other virtual machines seems to have an negative effect on the counter used as a reference by windows.

The more the CPU is preempted, the more the counter drifts.

Correcting the drift

By default, the Time Service has a “phase adjustment” process that slows down or speeds up the system clock rate to match a reliable time source. The TSC counter on the physical CPU is clocked by the system Quartz (If it is still like this). The “normal” drift of that kind of component is generally not very important, and may be related to external factors like the temperature of the room. The time service can deal with that kind of slow drift.

But the default configuration does not seem to be a good fit for a time source that drifts this quickly and is rather unpredictable. We need to shorten the process of phase adjustment.

Fixing this drift is rather simple, the Time Service needs to correct the clock rate more frequently, to cope with the load of the virtual machines that slow down the clock of the host.

Unfortunately, the default parameters on Hyper-V Server R2 are those of the default member of a domain, which are defined here. The default polling period from a reliable time source is way too long, 3600 seconds, considering the drift faced by the host clock.

A few parameters need to be adjusted in the registry for the clock to stay synchronized :

  • Set the SpecialInterval value to 0x1 to force the use of SpecialPollInterval.
  • Set SpecialPollInterval to 10, to force the source NTP to be polled every 10 seconds.
  • Set the MaxAllowedPhaseOffset to 1, to force the maximum drift to 1 second before the clock is set directly, if adjusting the clock rate failed.

Using these parameters will not mean that the clock will stay perfectly stable, but at the very least it will correct itself very quickly.

It seems that there is a hidden boot.ini parameter for Windows 2003, /USEPMTIMER, which forces windows to use the ACPI timer and avoid that kind of drift. I have not been able to confirm this has any effect at all, and I cannot confirm if the OS is actually using the PM Timer or the TSC.

REVISE: Expanding VHD or VDHX of VMs

Something to note on expanding VHD or VDHX of VMs

Question: Recover From Expanding VHD or VDHX Files On VMs With Checkpoints

Recover From Expanding VHD or VDHX Files On VMs With Checkpoints

Posted on October 1, 2015

So you’ve expanded the virtual disk (VHD/VHDX) of a virtual machine that has checkpoints (or snapshots as they used to be called) on it. Did you forget about them?  Did you really leave them lingering around for that long?  Bad practice and not supported (we don’t have production snapshots yet, that’s for Windows Server 2016). Anyway your virtual machine won’t boot. Depending on the importance of that VM you might be chewed out big time or ridiculed. But what if you don’t have a restore that works? Suddenly it’s might have become a resume generating event.

All does not have to be lost. Their might be hope if you didn’t panic and made even more bad decisions. Please, if you’re unsure what to do, call an expert, a real one, or at least some one who knows real experts. It also helps if you have spare disk space, the fast sort if possible and a Hyper-V node where you can work without risk. We’ll walk you through the scenarios for both a VHDX and a VHD.

How did you get into this pickle?

If you go to the Edit Virtual Hard Disk Wizard via the VM settings it won’t allow for that if the VM has checkpoints, whether the VM is online or not.

image

VHDs cannot be expanded on line. If the VM had checkpoints it must have been shut down when you expanded the VHD. If you went to the Edit Disk tool in Hyper-V Manager directly to open up the disk you don’t get a warning. It’s treated as a virtual disk that’s not in use. Same deal if you do it in PowerShell

Resize-VHD -Path “C:\ClusterStorage\Volume2\DidierTest06\Virtual Hard Disks\RuinFixedVHD.vhd” -SizeBytes 15GB

That just works.

VHDXs can be expanded on online if they’re attached to a vSCSI controller. But if the VM has checkpoints it will not allow for expanding.

image

So yes, you deliberately shut it down to be able to do it with the the Edit Disk tool in Hyper-V Manager. I know, the warning message was not specific enough but consider this. The Edit disk tool when launched directly has no idea of what the disk you’re opening is used for, only if it’s online / locked.

Anyway the result is the same for the VM whether it was a VHD or a VHDX. An error when you start it up.

[Window Title]

Hyper-V Manager

[Main Instruction]

An error occurred while attempting to start the selected virtual machine(s).

[Content]

‘DidierTest06’ failed to start.

Synthetic SCSI Controller (Instance ID 92ABA591-75A7-47B3-A078-050E757B769A): Failed to Power on with Error ‘The chain of virtual hard disks is corrupted. There is a mismatch in the virtual sizes of the parent virtual hard disk and differencing disk.’.

Virtual disk ‘C:\ClusterStorage\Volume2\DidierTest06\Virtual Hard Disks\RuinFixedVHD_8DFF476F-7A41-4E4D-B41F-C639478E3537.avhd’ failed to open because a problem occurred when attempting to open a virtual disk in the differencing chain, ‘C:\ClusterStorage\Volume2\DidierTest06\Virtual Hard Disks\RuinFixedVHD.vhd’: ‘The size of the virtual hard disk is not valid.’.

You might want to delete the checkpoint but the merge will only succeed for the virtual disk that have not been expanded.  You actually don’t need to do this now, it’s better if you don’t, it saves you some stress and extra work. You could remove the expanded virtual disks from the VM. It will boot but in many cased the missing data on those disks are very bad news. But al least you’ve proven the root cause of your problems.

If you inspect the AVVHD/AVHDX file you’ll get an error that states

The differencing virtual disk chain is broken. Please reconnect the child to the correct parent virtual hard disk.

image

However attempting to do so will fail in this case.

Failed to set new parent for the virtual disk.

The Hyper-V Virtual Machine Management service encountered an unexpected error: The chain of virtual hard disks is corrupted. There is a mismatch in the virtual sizes of the parent virtual hard disk and differencing disk. (0xC03A0017).

image

Is there a fix?

Let’s say you don’t have a backup (shame on you). So now what? Make copies of the VHDX/AVHDX or VHD/AVHD and save guard those. You can also work on copies or on the original files.I’ll just the originals as this blog post is already way too long. If you. Note that some extra disk space and speed come in very handy now. You might even copy them of to a lab server. Takes more time but at least you’re not working on a production host than.

Working on the original virtual disk files (VHD/AVHD and / or VHDX/AVHDX)

If you know the original size of the VHDX before you expanded it you can shrink it to exactly that. If you don’t there’s PowerShell to the rescue if you want to find out the minimum size.

image

But even better you can shrink it to it’s minimum size, it’s a parameter!

Resize-VHD -Path “C:\ClusterStorage\Volume2\DidierTest06\Virtual Hard Disks\RuinFixedVHD.vhd” -ToMinimumSize

Now you not home yet. If you restart the VM right now it will fail … with the following error:

‘DidierTest06’ failed to start. (Virtual machine ID 7A54E4DB-7CCB-42A6-8917-50A05354634F)

‘DidierTest06’ Synthetic SCSI Controller (Instance ID 92ABA591-75A7-47B3-A078-050E757B769A): Failed to Power on with Error ‘The chain of virtual hard disks is corrupted. There is a mismatch in the identifiers of the parent virtual hard disk and differencing disk.’ (0xC03A000E). (Virtual machine ID 7A54E4DB-7CCB-42A6-8917-50A05354634F)

image

What you need to do is reconnect the AVHDX to it’s parent and choose to ignore the ID mismatch. You can do this via Edit Disk in Hyper-V Manager of in PowerShell. For more information on manually merging & repairing checkpoints see my blogs on this subject here. In this post I’ll just show the screenshots as walk through.

image
image
image
image
image

Once that’s done you’re VHDX is good to go.

For a VHD you can’t shrink that with the inbox tools. There is however a free command line tool that can do that names VHDTool.exe. The original is hard to find on the web so here is the installer if you need it. You only need the executable, which is portable actually, don’t install this on a production server. It has a repair switch to deal with just this occurrence!

Here’s an example of my lab …

D:\SysAdmin>VhdTool.exe /repair “C:\ClusterStorage\Volume2\DidierTest06\Virtual Hard Disks\RuinFixedVHD.vhd” “C:\ClusterStorage\Volume2\DidierTest06\Virtual Hard Disks\RuinFixedVHD_8DFF476F-7A41-4E4D-B41F-C639478E3537.avhd”

image

That’s it for the VHD …

Winking smile

You’re back in business!  All that’s left to do is get rid of the checkpoints. So you delete them. If you wanted to apply them an get rid of the delta, you could have just removed the disks, re-added the VHD/VHDX and be done with it actually. But in most of these scenarios you want to keep the delta as you most probably didn’t even realize you still had checkpoints around. Zero data loss .

Conclusion

Save your self the stress, hassle and possibly expense of hiring an expert.  How? Please do not expand a VHD or VHDX of a virtual machine that has checkpoints. It will cause boot issues with the expanded virtual disk or disks! You will be in a stressful, painful pickle where you might not get out of if you make the wrong decisions and choices!

As a closing note, you must have have backups and restores that you have tested. Do not rely on your smarts and creativity or that others, let alone luck. Luck runs out. Otions run out. Even for the best and luckiest of us. VEEAM has save my proverbial behind a few times already.

Question: Hyper-V VHD Expand and keeping snapshots?

1down votefavorite

1

I have a Virtual Machine and it includes OS and other programs of course. ATM I have around 5 Snapshots.

The Disk Space is running low and I wanted to expand the VHD. I enter VM’s settings and intend to edit the VHD and expand the VHD but all i found was this messege.

enter image description here

So are there other ways of expanding a VHD? I simple wondered if there is a way to keep the snapshots and expand the virtual hard disk. I realize that there might be problems if i remove them and then import them again.

Answer:

Remove your snapshots and then expand the disk. You should read up on how snapshots work, because that will explain why expanding the underlying VHD will be bad news for the delta disks.

Answer:

0down vote

It may not have been possible when the original answer was written, but you can merge your snapshots into a new VHDX.

  1. Look up the path to the disk image for the snapshot you want to expand in the snapshot settings.
  2. Using the Hyper-V Manager -> Action -> Edit Disk, select the snapshot .avhx file.
  3. Through the wizard, choose to merge the snapshot disk to a new dynamic .vhdx image. You should be able to configure a new size at this point.
  4. When it’s done, you can change your snapshot settings to point to the new .vhdx image.

VMWare/Hyper-V Snapshot Issue

Can not edit vhd, because the system thinks snapshots exist, but I disagree

Never resize a VHD with snapshots or differencing disks – more about differencing disks

Q & A: Expanding VHDX files

Expanding a VHDX Disk on Hyper-V

REVISE: Hyper-V Remote Management Using Powershell

Question: remote management powershell

PowerShell Remoting is Secure

 PowerShell Enables Any Version of Windows to Remotely Manage Any Other Version of Windows (and Hyper-V)

A very common complaint, and sometimes an outright problem, is that Hyper-V Manager can only fully control versions of Hyper-V that are running on the same code base. Hyper-V Manager in Windows 7 can’t control anything after the version of Hyper-V that released with the Windows 7/Windows Server 2008 R2 code base. Windows 8 or later was required. Starting in Windows 8/Server 2012, Hyper-V Manager can usually manage down-level hosts, but some people have troubles even with that.

With PowerShell, there’s no problem. PowerShell Remoting was introduced in PowerShell 2.0, and since then, PowerShell Remoting has worked perfectly well both up-level and down-level. The following is a screenshot of a Windows 7 installation with native PowerShell 2.0 remotely controlling a Hyper-V 2012 R2 server with native PowerShell 4.0:

PSRemoting Different Versions

PSRemoting Different Versions

How to Enable PowerShell Remoting for Hyper-V

Both the local and remote systems must be set up properly for PowerShell Remoting to work. The first thing that you must do on both sides is:

1Enable-PSRemoting -Force

On non-domain-joined systems, I received an “Access Denied” error unless I used the real Administrator account; just using an account in the local administrators group wasn’t enough. This seems to be at odds with the normal Windows authentication model and was just plain annoying for Windows 7, which disables the Administrator account by default. You can try the SkipProfileCheck parameter… it might help.

Installing the PowerShell Hyper-V Module

Not surprisingly, the easiest way to install the Hyper-V PowerShell module is with PowerShell. This works on Windows 8 and later, Windows Server 2012 and later, and Hyper-V Server 2012 and later:

1Install-WindowsFeature Hyper-V-PowerShell

If you’d like to install Hyper-V Manager along with the PowerShell module:

1Install-WindowsFeature RSAT-Hyper-V-Tools

If you’d like to install both of these tools along with Hyper-V:

1Install-WindowsFeature Hyper-V -IncludeManagementTools

If you’d rather take the long way through the GUI for some reason, your approach depends on whether or not you’re using a desktop or a server operating system.

For a desktop, open Turn windows features on or off via the Control Panel. Open the Hyper-V tree, then the Hyper-V Management Tools subtree, and check Hyper-V Module for Windows PowerShell (along with anything else that you’d like).

Hyper-V PowerShell Module on Windows

Hyper-V PowerShell Module on Windows

For a Server operating system, start in Server Manager. Click Add roles and features. Click through all of the screens in the wizard until you reach the Features page. Expand Remote Server Administration Tools, then Hyper-V Management Tools, and check Hyper-V Module for Windows PowerShell (along with anything else that you’d like).

Server Hyper-V PowerShell Module

Server Hyper-V PowerShell Module

Once the module is installed, you can use it immediately without rebooting. You might need to import it if you’ve already got an open PowerShell session, or you could just start a new session.

Implicit PowerShell Remoting in the Hyper-V Module

The easiest way to start using PowerShell Remoting is with implicit remoting. As a general rule, cmdlets with a ComputerName parameter are making use of implicit remoting. What that means is that all of the typing is done on your local machine, but all of the action occurs on the remote machine. Everything that the Hyper-V module does is in WMI, so this means that all of the commands that you type are being sent to the VMMS service on the target host to perform. If you are carrying this out interactively, the results are then returned to your console in serializedform.

To make use of implicit remoting with the Hyper-V module, you must have it installed on your local computer. There are more limitations on implicit remoting:

  • You can only (legally) install the Hyper-V PowerShell module that matches your local Windows version
  • You are limited to the functionality exposed by your local Hyper-V PowerShell module
  • No matter the local version, it cannot be used to manage 2008 R2 or lower target hosts
  • Implicit remoting doesn’t always work if the local and remote Hyper-V versions are different

For example, I cannot install the Hyper-V PowerShell module at all on Windows 7. As another example, the Hyper-V PowerShell module in Windows 10 cannot control a 2012 R2 environment. Basically, the Hyper-V PowerShell module on your local system follows similar rules as Hyper-V Manager on your local system. I want to reiterate that these rules only apply to implicit remoting; you can still explicitly operate any cmdlet in any module that exists on the target.

For example, from my Windows 10 desktop, I run Get-VM -CompterName svhv01 against my Windows Server 2016 TP5 host:

Implicit Remote Get-VM

Implicit Remote Get-VM

Behind the scenes, it is directing WMI on SVHV01 to run “SELECT * FROM Msvm_ComputerSystem” against its “root\virtualization\v2” namespace. It is then processing the results through a local view filter.

Implicit Remoting Against Several Hosts

I was saying how PowerShell Remoting can be used against multiple machines at once. Any time that a cmdlet’s ComputerName parameter supports a string array, you can operate it against multiple machines. Run Get-Help against the cmdlet in question and check to see if the ComputerName parameter has square brackets:

ComputerName with Array Support

ComputerName with Array Support

As you can see, Get-VM has square brackets in its ComputerName parameter (the [<String[]>]] part), so it can accept multiple hosts. Example:

1Get-VM -ComputerName svhv01, svhv02

Locking Implicit Remoting to a Specific Host

I have a complex environment with several hosts, so I am content to always specify the -ComputerName parameter as necessary. If you’ve only got a single host, then you might like to avoid typing that ComputerName parameter each time. To do that, open up your PowerShell profile and enter the following:

123Get-Command –Module Hyper-V –Verb Get | foreach { $PSDefaultParameterValues.Add(“$($_.Name):ComputerName”,”TARGETHOSTNAME”)}

Just replace TARGETHOSTNAME with the name or IP address of your remote host. From that point onward, any time you open any PowerShell prompt using the modified profile, all cmdlets from the Hyper-V module that start with “Get” will be automatically injected with “-ComputerName TARGETHOSTNAME”.

Implicit Remoting and the Pipeline

It can take some time and practice to become accustomed to how the pipeline works with implicit remoting, not least of which because some cmdlets behave differently. As a general rule, the pipeline brings items back to your computer.

So, let’s say you did this:

1Get-VM -ComputerName | Export-CSV -Path d:\temp\svhv02VMList.csv -NoTypeInformation

Where do you expect to find the file? On the remote host or the local host?

Implicit Remoting with a Pipeline

Implicit Remoting with a Pipeline

The file was created on my local system (if you looked closely at my screenshot and it made you curious, the file is zero length because there are no VMs on that system, not because it failed).

So, what this behavior means to you is that if you choose to then carry out operations on the objects such as Set cmdlets, you might need to use implicit remoting again after a pipeline… but then again, you might not. Which of the following do you think is correct?

  1. 1Get-VM -ComputerName svhv01 | Set-VMMemory -MaximumBytes 2.5GB
  2. 1Get-VM -ComputerName svhv01 | Set-VMMemory -ComputerName svhv01 -MaximumBytes 2.5GB

If you said #1, then you’re right! But, do you know why? It’s actually fairly simple to tell. Just look at the object that is crossing the pipeline:

Computer Name on Object

Computer Name on Object

The object contains its computer name and the cmdlets in the Hyper-V module are smart enough to process it as an object that contains a computer name. To then specify the computer name again for the cmdlet to the right of the pipeline just confuses PowerShell and causes it to error. Not all objects have a ComputerName property and not all cmdlets know to look for it. Furthermore, if you do anything to strip away that property and then try to pipe it to another cmdlet, you will need to specify ComputerName again. For example:

1Get-VM -ComputerName svhv01 | select Name | % { Set-VMMemory -ComputerName svhv01 -MaximumBytes 2.5GB -VMName $_.Name }

Explicit Remoting

If the remote host has the PowerShell module installed, you can establish a session to it and begin work immediately. Natively, this requires the target system to be 2012 or later, as there was no official Hyper-V PowerShell module in prior versions. There is an unofficial release for 2008 R2 (and maybe 2008, I never tried). Explicit remoting is “harder” than implicit remoting (requires more typing) but is much more powerful and there are no fancy rules governing it. If you can connect to the remote machine using PowerShell Remoting, then you can operate any PowerShell cmdlets there (for the PowerShell experts, just imagine that there is an asterisk right here that links to a mention of Constrained Endpoints).

There are two general ways to use explicit remoting. The first is to use Enter-PSSession. That drops you right onto the remote console as a sort of console-within-a-console. From there, you can work interactively. The second method is to encapsulate script in a block and feed it to Invoke-Command. That method is used for scripting and automatically cleans up after itself.

PowerShell Remoting in an Interactive Session

The simplest way to remotely connect to an interactive PowerShell session is:

1Enter-PSSession hostname

As shown, the command only works between machines on the same domain and when the current user account has sufficient privileges. I showed this above, but for the sake of completeness, to connect when one of the computers is unjoined or untrusted and/or if the user account is not administrative:

1Enter-PSSession hostname -Credential (Get-Credential)

This will securely prompt you for the credentials to use on the target. If the target is domained-joined, make sure you use the format of domain\username. If it’s a standalone system, you can use the username by itself or computername\username.

If the remote system is using SSL:

1Enter-PSSession hostname -Credential (Get-Credential) -UseSSL

Once the connection is established, it will change the prompt to reflect that you’re accessing the remote computer. You can see examples in the screenshots above. It will look like this:

1[hostname]: PS C:\Users\UserAccount\Documents>

One thing I generally avoid in instructional text is using positional parameters. I especially dislike mixing positional and named parameters. I’ve done both here for the sake of showing you how uncomplicated PowerShell Remoting is to use. For the purposes of delivering a proper education, be aware that the named parameter that you use to specify the host name is -ComputerName . As long as it’s the first parameter submitted to the cmdlet, you don’t have to type it out.

Once you’re connected, it’s mostly like you were sitting at a PowerShell prompt on the remote system. Be aware that any custom PowerShell profile you have on that host isn’t loaded. Also note that whatever you’re doing on that remote system stays on that system. For instance, you can’t put something into a variable and then call that variable from your system after you exit the session.

When you’re done, you can just close the PowerShell window. PowerShell will clean up for you. If you want to go back to working on your computer:

1Exit-PSSession

I much prefer the shorter alias:

1exit

Using PowerShell Remoting to Address the Remote Device Manager Problem

Now that you know how to connect to a remote PowerShell session, you have the ability to overcome one of the long-standing remote management challenges of both Windows and Hyper-V Server. Prior to the 2012 versions, you could remotely connect to Device Manager, but only in a read-only mode. Starting in 2012, even that is gone.

You can get driver information for a lot of devices using PowerShell. For example, Get-NetAdapter returns several Driver fields. But what about installing or upgrading drivers? That was never possible using Device Manager remotely, or even through other remote tools. Well, with PowerShell Remoting, the problem is solvable.

You’re not restricted to running PowerShell commands inside your remote session. You can run executables, batch files, and other such things. The only things you can’t do is initiate a GUI or start anything that has its own shell. Fortunately, one of the things that can be run is pnputil. This utility can be used to manage drivers on a system. So, with PowerShell Remoting, you can remotely install and upgrade drivers.

My systems use Broadcom NICs as their management adapters. I downloaded the drivers and transferred them into local drives on my hosts. Then, using PowerShell Remoting from my desktop, I connected in and used pnputil to install them. The command to install a driver is:

1pnputil -i -a driverfile.inf

You can see the results for yourself:

Remote PNPUTIL Driver Installation

You can see that, as expected, my network connection was interrupted. What’s not shown is that PowerShell used a progress bar to show its automatic reconnection attempts. Once the driver was installed, the session automatically picked up right where it left off.

For verification, you can use pnputil -e :

Remote PNPUTIL Driver Enumeration

Windows replaces the original driver file name with OEM#, as you can see here, but it keeps the manufacturer name and the driver version and date. If you want further verification, you can also run Get-NetAdapter | fl Driver* .

Advanced PowerShell Remoting with Invoke-Command

Here’s where the fun begins. Where the remote session usage shown above is great for addressing immediate needs, the true power of PowerShell Remoting is in connecting to multiple machines. Invoke-Command is the tool of choice:

1Invoke-Command -ComputerName svhv1, svhv2 -ScriptBlock { Get-VM }

If you run the above on systems prior to 2016, the first thing you’ll likely notice is that there’s no prettification of the output. Get-VM usually looks like this:

Demo Get-VM

That’s because there’s a defined custom formatting view being applied. When an object crosses back to a source system across Invoke-Command , no view is applied. What you get is mostly the same thing you’d see if you piped it through  Format-List -Property *  (mostly seen as  | fl *  ).

At this point, it might not make any sense why we’re doing this. This is the same output that we got from the implicit remoting earlier, but it required more typing, and more to remember.

If you have any VMs, the above cmdlets produce a wall of text. Let’s slim it down a bit. From PowerShell 2.0 in Windows 7, I ran  Invoke-Command -Computer svhv1, svhv2 -Credential (Get-Credential) -UseSSL -ScriptBlock { Get-VM | select Name }. Here’s the output:

Get-VM through Invoke-Command

Running the same script block locally would have resulted in a table with just the name column. Here, I get three more: PSComputerName, RunspaceId, and PSShowComputerName. In PowerShell 3.0 and later, the PSShowComputerName column isn’t there anymore. The benefit here is that you can use these fields to sort the output by the system that sent it.

You can use  -HideComputer with  Invoke-Command  to suppress the output of all the extra fields if your source system is running PowerShell 3.0 or later. For PowerShell 2.0, RunspaceId is still shown but the others are hidden. They’re still there, so you can query against them. What’s nice about this is, if your system has the related module installed, then any custom formatting views will be applied just as if you were running inside a connected session:

Invoked Get-VM with -HideComputerName

This formatting issue is no longer a concern in Windows 10/Windows Server 2016 (which I suspect is more due to changes in PowerShell 5 than in the Hyper-V module):

PowerShell Remoting Formatting in 2016

PowerShell Remoting Formatting in 2016

Being able to format the output will always be a useful skill even with the basic formatting issues automatically addressed.

It might not make sense why we’re doing things this way. The implicit remoting method that I showed you earlier did just as well, and it required less to type (and memorize). The first reason that you’d use this method is because it doesn’t matter if the local computer and the remote computer are running the same versions of anything. The PowerShell 2.0 examples on Windows 7 that I showed you were running against a Hyper-V Server 2012 R2 environment. Neither the Windows 7 nor my Windows 10 environment can even run implicit remoting against those systems.

Even more importantly, this doesn’t begin to show the true power of PowerShell Remoting. Let’s do some interesting things. For instance, looking at VM output is fun and all, but why stop there? How about:

$RemoteVMs = Invoke-Command -Computer svhv1, svhv2 -Credential (Get-Credential) -UseSSL -ScriptBlock { Get-VM }

What I’ve done here is connect in to both hosts, retrieve their virtual machines, store them in a variable on my computer, and then disconnected the remote session. I can store them, format the output, build reports, etc. What I can’t do is make any changes to them, but that’s OK. I’ve got a couple of answers to that.

First, I can perform the modifications right on the target system by using a more complicated script block. The following example builds a script that retrieves all the VMs that aren’t set to start automatically and sets them so that they do. That entire script is assigned to a variable named “RemoteVMManipulation”. I use that as the  -ScriptBlock parameter in an Invoke-Command , which I send to each of the hosts. The result of the script is saved to a variable:

123456789$RemoteVMManipulationBlock = {    $VMsNotStartingAutomatically = Get-VM | where { $_.AutomaticStartAction -ne “Start” }    foreach ($VM in $VMsNotStartingAutomatically)    {        Set-VM -VM $VM -AutomaticStartAction Start    }    $VMsNotStartingAutomatically}$ModifiedVMs = Invoke-Command -ComputerName svhv1, svhv2 -ScriptBlock $RemoteVMManipulationBlock

This isn’t the most efficient script block, but I wrote it that way for illustration purposes. The variable “VMsNotStartingAutomatically” is created on each of the remote systems, but is destroyed as soon as the script block exits. It is not retrievable or usable on my calling system. However, I’ve placed the combined output into a variable named “ModifiedVMs”. Like a local function call, the output is populated by whatever was in the pipeline at the end of the script block’s execution. In this case, it’s the “VMsNotStartingAutomatically” array. Upon return, this array is transferred to the “ModifiedVMs” variable, which lives only on my system. In subsequent lines of the above script, I can view the VM objects that were changed even though the remote sessions are closed.

The second way to manipulate the objects that were returned is to transmit them back to the remote hosts using the -InputObject  parameter and keep track of them with the added “PSComputerName” field:

12345678910111213$RemoteVMManipulationBlock = {    foreach ($VMList in $input)    {        foreach($VM in $VMList)        {            if($VM.PSComputerName -eq $env:COMPUTERNAME)            {                Set-VM -VMName $VM.Name -AutomaticStartAction StartIfRunning            }        }    }}Invoke-Command -ComputerName svhv1, svhv2 -ScriptBlock $RemoteVMManipulationBlock -InputObject $ModifiedVMs

What I’ve done here is send the “ModifiedVMs” variable from my system into each of the target systems using the-InputObject parameter. Once inside the script block, you reference this variable with $input . There are a few things to note here. For one, you’ll notice that I had to unpack the “ModifiedVMs” variable two times. For another, I wasn’t able to reference the input items as VM objects. Instead, I had to point it to the names of the VMs. This is because we’re not sending in true VM objects. We’re sending in what we got. GetType() reveals them as:

1Deserialized.Microsoft.HyperV.PowerShell.VirtualMachine

Because they’re a different object type, parameters expecting an object of the type “Microsoft.HyperV.PowerShell.VirtualMachine” will not work. Objects returned from Invoke-Command are always deserialized, which is why you have to go through these extra steps to do anything other than look at them. If you’ve got decent programming experience or you just don’t care about these sorts of things, you can skip ahead to the next section.

Serialization and deserialization are the methods that the .Net Framework, which is the underpinning of PowerShell, uses to first package objects for uses other than in-memory operations, and then to unpackage them later. There are lots of definitions out there for the term “object” in computer programming, but they are basically just containers. These containers hold only two things: memory addresses and an index of those memory addresses. The contents at those memory addresses are really just plain old binary 0s and 1s. It’s the indexes that give them meaning. How exactly that’s done from the developer’s view is dependent upon the language. So, in C++, you might find a “variable” defined as “int32”. This means that the memory location referenced by the index is 32 bits in length and the contents of those 32 bits should be considered an integer and that those contents can be modified. Indexes come in two broad types: data and code. In (a perhaps overly simplistic description of) .Net, data indexes are properties and refer to constants and variables. Code indexes can be either methods or events, and refer to functions.

As long as the objects are in memory, all of this works pretty much as you’d expect. If you send a read or write operation to a data index, then the contents of memory that it points to are retrieved or changed, respectively. If you (or, for an event, the system) call on a code index, then the memory contents it refers to are processed as an instruction set.

What happens if you want to save the object, say to disk? Well, you probably don’t care about the memory locations. You just want their contents. As for the functions and events, those have no meaning once the object is stored. So, what has to happen is all the code portions need to be discarded and the names of the indexes need to be paired up with the contents of the memory that they point to. As mentioned earlier, the .Net Framework does this by a process called serialization. Once an object is serialized, it can be written directly to disk. In our case, though, the object is being transmitted back to the system that called Invoke-Command .  Once there, it is deserialized so that its new owning system can manipulate it in-memory like any other object. However, because it came from a serialized object, its structure looks different than the original because it isn’t the same object.

You’ll notice that all the events are gone. The only methods are GetType() and ToString(), which are part of this new object, not carried over from the original, and are here because they exist on every PowerShell object. Properties that contained complex objects have also been similarly serialized and deserialized.

Using Saved Credentials and Multiple Sessions

Of course, what puts the power into PowerShell is automation. Automation should mean you can “set it and forget it”. It’s tough to do that if you have to manually enter information into Get-Credential, isn’t it?

There’s also the problem of multiple credential sets. Hopefully, if you’ve got more than one host that sits outside your domain, they’ve each got their own credentials. I know that some people out there put Hyper-V systems in workgroup mode “to protect the domain” but then use a credential set with the same user name and password as their domain credentials. It’s no secret that I see no value in workgroup Hyper-V hosts when a domain is available except for perimeter networks, but if you’re going to do it, at least have the sense to use unique user names and passwords. Sure, it can be inconvenient, but when you actively choose the micro-management hell of workgroup-joined machines, you can’t really be surprised when you find yourself in micro-management hell. Fortunately for you, PowerShell Remoting can take a lot of the sting out of it.

The first step is to gather the necessary credentials for all of your remote machines and save them into disk files on the system where you’ll be running Invoke-Command. For that bit, I’m just going to pass the buck to Lee Holmes. He does a great job explaining both the mechanism and the safety of the process.

Once you have the credentials stored in variables, you next create individual sessions to the various hosts.

12$SVHV1Session = New-PSSession -ComputerName svhv1 -Credential $SVHV1Credential$SVHV2Session = New-PSSession -ComputerName svhv2 -Credential $SVHV2Credential

You’re all set. You use the sessions like this:

1$RemoteVMs = Invoke-Command -Session $SVHV1Session, $SVHV2Session -ScriptBlock { Get-VM }

Of course, if you’ve only got one remote host but you want to use credentials retrieved from disk, you don’t need the sessions:

1$RemoteVMs = Invoke-Command -ComputerName svhv1 -Credential $SVHV1Credential -ScriptBlock { Get-VM }

One thing to remember though, is that sessions created with New-PSSession will persist, even if you close your PowerShell prompt. They’ll eventually time out, but until then, they’re like a disconnected RDP session. They just sit there and chew up resources, giving an attackers an open session to attempt to compromise, all for no good reason. If you want, you can reconnect and reuse these sessions. Otherwise, get rid of them:

12$SVHV1Session | Remove-PSSession$SVHV2Session | Remove-PSSession

Or, to close all:

1Get-PSSession | Remove-PSSession

For More Information

I’ve really only scratched the surface of PowerShell Remoting here. I had heard about it some time before, but I wasn’t in a hurry to use it because I was “getting by” with Hyper-V Manager and Remote Desktop connections. Ever since I spent a few minutes learning about Remoting, I have come to use it every single day. The ad hoc capabilities of Enter-PSSession allow me to knock things out quickly and the scripting powers of Invoke-Command are completely irreplaceable.

All that, and I haven’t even talked about delegated administration (allowing a junior admin to carry out a set of activities as narrowly defined as you like via a pre-defined PowerShell Remoting session) or implicit remoting or setting up “second hop” powers so you can control other computers from within your remote session. For those things, and more, you’re going to have to do some research on your own. I recommend starting with PowerShell in Depth. Most of the general information, but not all, of what you saw in this article can be found in that book. That chapter does contain all the things I teased about, and more.

Question: VMs with PowerShell SCVMM or Hyper-V Manager

Hyper-V Manager, SCVMM and PowerShell can all be used to create a Hyper-V VM, but if you want to configure certain parameters beforehand, you need to use SCVMM.

There are several ways to create VMs on Hyper-V virtualization hosts. The standard approach is to use Hyper-V Manager or System Center Virtual Machine Manager. However, many administrators like to use PowerShell cmdlets to quickly provision Hyper-V VMs. PowerShell is a very useful tool for when you need to deploy Hyper-V VMs in a development environment or when you need to perform VM creation tasks repeatedly.

Create Hyper-V VMs using Hyper-V Manager

Most Hyper-V administrators are familiar with the VM creation process using Hyper-V Manager. All you need to do is open Hyper-V Manager, right-click on a Hyper-V host in the list of available hosts, click on the New action, click on the Virtual Machine action and then follow the steps on the screen to create the VM. You’ll need to specify parameters, like VM name, VM generation and the path to store VM files.

Create Hyper-V VMs using SCVMM

Deploying VMs using System Center Virtual Machine Manager (SCVMM) is fairly simple. You can deploy VMs on a standalone Hyper-V host or in a Hyper-V cluster. You need to go to the VMs and Services workspace, right-click on a SCVMM host group and then click on the Create Virtual Machine action

When you click on the Create Virtual Machine action, SCVMM will open a wizard. All you need to do is follow the steps on the screen. One of the main advantages of SCVMM is that it allows you to configure VM parameters — including Dynamic Memory — before the actual creation process starts. Another benefit of using SCVMM is that you can quickly provision a VM by selecting a SCVMM template that already includes the required VM settings. SCVMM also provides greater flexibility when deploying VMs in a production environment.

When you provision VMs using SCVMM, SCVMM creates a PowerShell script on the fly and then executes it via the SCVMM job window. If you need to use the PowerShell script where SCVMM isn’t installed, you can copy the PowerShell script from the SCVMM job window and modify the Hyper-V host-related parameters.

Create Hyper-V VMs using PowerShell

Hyper-V offers the New-VM PowerShell cmdlet that can be used to create a VM on a local or remote Hyper-V host. It’s important to note that, before creating Hyper-V VMs using PowerShell, you’ll need to make some configuration decisions, as explained below:

  • Figure out the Hyper-V virtual switch to which the VM will be connected. You can get Hyper-V virtual switch names by executing the Get-VMSwitch * | Format-Table NamePowerShell command. The command will list all the Hyper-V virtual switches on the local Hyper-V host. Copy the Hyper-V virtual switch name to be used in the VM creation command.
  • Decide the type of memory configuration for the new VM. Are you planning to use static memory or Dynamic Memory? If you plan to use the Dynamic Memory feature, you’ll need to use the Set-VMMemory PowerShell cmdlet after creating the VM.
  • Identify the VM file path where VM files will be stored. It can be a local path, a path to the Cluster Shared Volumes disk in the Hyper-V cluster or a path to the Scale-Out File Server cluster.
  • Decide if you’d like the OS in the VM to be installed via a Preboot Execution Environment server running on the network or if you’d like to set up the OS from a DVD. Depending on the OS deployment type, you’d want to change the boot order of the VM.
  • Are you going to create a new VM on a local or remote Hyper-V host? If you’re going to create a VM on a remote Hyper-V host, get the Hyper-V server’s fully qualified domain name or IP address, and specify that value using the -ComputerName parameter in the New-VMPowerShell cmdlet.
  • Choose the generation of the VM. Generation 2 VMs provide new features, such as guest clustering, Hyper-V virtual hard disk (VHDX) online resizing, secure boot, fast boot and so on. I recommend you choose Generation 2 unless you have a reason to go for Generation 1 VMs.

Once you have gathered the required parameters for the new VM, use the PowerShell command below to create the VM on the Hyper-V host.

New-VM –Name SQLVM –MemoryStartupBytes 8GB –BootDevice VHD –VHDPath C:\ProductionVMs\SQLVM.VHDX –Path C:\ProductionVMs\VMFiles –Generation 2 –Switch ProductionSwitch

This command will create a VM by the name of the SQLVM on the local Hyper-V host. The new VM will be configured to use 8 GB of memory and will be stored in the C:\ProductionVMs folder. Note that -Generation 2 specifies that this VM will be created as a Generation 2 VM. If you want to change the new VM’s memory configuration from static to Dynamic Memory, use the PowerShell command below:

Stop-VM –Name SQLVM

Set-VMMemory SQLVM –DynamicMemoryEnabled $True –MinimumBytes 250MB –StartupBytes 500MB –MaximumBytes 8GB –Priority 70 –Buffer 20

These commands configure the SQLVM with Dynamic Memory and set the required parameters for Dynamic Memory.

Question: run powershell commands against a remote vm

Here’s a look at the Invoke-Command cmdlet and how it will be extended in Windows Server 2016.

PowerShell is one of Microsoft’s preferred tools for managing Windows Servers. Although it’s easy to think of PowerShell as a local management tool, PowerShell can just as easily be used to manage other servers in your datacenter. This capability is especially helpful if you have a lot of Hyper-V virtual machines and want to be able to perform bulk management operations.

There are a few different ways of running a PowerShell command against a remote server. For the purposes of this article however, I want to show you how to use the Invoke-Command cmdlet. The reason why I want to talk about this particular method is because the Invoke-Command cmdlet is being extended in Windows Server 2016 to provide better support for Hyper-V virtual machines. I will get to that in a few minutes.

The first thing that you will need to do is to configure the remote system to allow for remote management. Microsoft disables remote PowerShell management by default as a way of enhancing security.

To enable remote PowerShell management, logon to the remote server, open PowerShell (as an Administrator) and run the following command:

Enable-PSRemoting –Force

This command does a few different things. First, it starts the WinRM service, which is used for Windows remote management. It also configures the service to start automatically each time that the server is booted and it also adds a firewall rule that allows inbound connections. In case you are wondering, the Force parameter is used for the sake of convenience. Without it, PowerShell will nag you for approval as it performs the various steps. You can see what the command looks like in action in Figure 1.

[Click on image for larger view.]  Figure 1. You must use the Enable-PSRemoting cmdlet to prepare the remote server for management.

There are about a zillion different ways that you can use the Invoke-Command cmdlet. Microsoft provides full documentation for using this cmdlet here. This site covers the full command syntax in ponderous detail. For the purposes of this article however, I want to try to keep things simple and show you an easy method of running a command against a remote system.

The first thing that you need to know is that any time you are going to be running a PowerShell command against a remote system, you will have to enter an authentication credential. Although this step is necessary, it is a bit of a pain to enter a set of credentials every time you run a command. Therefore, my advice is to map your credentials to a variable. To do so, enter the following command:

$Cred = Get-Credential

As you can see in Figure 2, entering this command causes PowerShell to prompt you for a username and password. The credentials that you enter are mapped to the variable $Cred.

[Click on image for larger view.]  Figure 2. Your credentials can be mapped to a variable.

Now that your credentials have been captured, the easiest way to run a command against a remote server is by using the following syntax:

Invoke-Command –ComputerName <server name> -Credential  $Cred –ScriptBlock{The command that you want to run}

OK, so let’s take a look at how this command works. Right now I am using PowerShell on a system that is running Windows 8.1. I have a Hyper-V server named Hyper-V-4. Let’s suppose that I want to run the Get-VM cmdlet on that server so that I can find out what virtual machines currently exist on it. To do so, I would use this command:

Invoke-Command –ComputerName Hyper-V-4 –Credential $Cred  –ScriptBlock{Get-VM}

As you can see, the script block contains the command that needs to be executed on the remote system. It is worth noting that this technique only works if both computers are domain joined and are using Kerberos authentication. Otherwise, you will have to use the HTTPS transport or add the remote computer to a list of trusted hosts. The previously mentioned TechNet article contains instructions for doing so.

At the beginning of this article, I mentioned that Invoke-Command was being extended in Windows Server 2016 to better support Hyper-V virtual machines. Microsoft is adding a parameter named VMName (which is used in place of ComputerName). This extension makes use of a new feature called PowerShell direct, which allows you to run PowerShell commands on a Hyper-V virtual machine even if the virtual machine is not connected to the network. This is accomplished by communicating with the VM through the VMBus.

So as you can see, the Invoke-Command cmdlet makes it easy to manage remote servers through PowerShell. I would encourage you to check out the previously mentioned TechNet article because there is a lot more that you can do with the Invoke-Command cmdlet than what I have covered here.

Question: managing hyper-v server remotely through powershell

Working with PowerShell can be very common for daily tasks and Hyper-V Server management. However, as there is more than one server to be managed, sometimes it can be difficult to log on and run the PowerShell scripts (most of the time the same one) on different computers.

One of the benefits that PowerShell offers is the remote option that allows you to connect to multiple servers, enabling a single PowerShell window to administer as many servers as you need.

The PowerShell remote connection uses port 80, HTTP. Although the local firewall exception is created by default when it’s enabled, make sure that any other firewall has the exception to allow communication between your servers.

How to do it

These tasks will show you how to enable the PowerShell Remoting feature to manage your Hyper-V Servers remotely using PowerShell.

1. Open a PowerShell window as an administrator from the server for which you want to enable the PowerShell Remoting.

2. Type the Enable-PSRemoting commandlet to enable PowerShell Remoting.

3. The system will prompt you to confirm some settings during the setup. Select A for Yes to All to confirm all of them. Run the Enable-PSRemoting command on all the servers that you want to connect to remotely via PowerShell.

4. In order to connect to another computer in which the PowerShell Remoting is already enabled, type Connect-PSSession Hostname, where hostname is the computer name to which you want to connect.

5. To identify all the commands used to manage the PowerShell sessions, you can create a filter with the command Get-Command *PSSession*. A list of all the PSSession commands will appear, showing you all the available remote connection commands.

6. To identify which command lines from Hyper-V can be used with the remote option computername, use the Get-Commandwith the following parameter:

Get-Command –Module Hyper-V –ParameterName Computername

7. To use the remote PowerShell connection from PowerShell ISE, click on File and select New Remote PowerShell Tab. A window will prompt you for the computer name to which you want to connect and the username, as shown in the following screenshot. Type the computer name and the username to create the connection and click on Connect. Make sure that the destination computer also has the remoting settings enabled.

clip_image002

8. A new tab with the computer name to which you have connected will appear at the top, identifying all the remote connections that you have through PowerShell ISE. The following screenshot shows an example of a PowerShell ISE window with two tabs. The first one to identify the local connection called PowerShell 1 and the remote computer tab called HVHost.

clip_image004

Summary

The process to enable PowerShell involves the creation of a firewall exception, WinRM service configuration, and the creation of a new listener to accept requests from any IP address. PowerShell configures all these settings through a single and easy command—Enable-PSRemoting. By running this command, you will make sure that your computer has all the components enabled and configured to accept and create new remote connections using PowerShell.

Then, we identified the commands which can be used to manage the remote connections. Basically, all the commands that contain PSSession in them. Some examples are as follows:

· Connect-PSSession to create and connect to a remote connection

· Enter-PSSession to connect to an existing remote connection

· Exit-PSSession to leave the current connection

· Get-PSSession to show all existing connections

· New-PSSession to create a new session

Another interesting option that is very important, is to identify which commands support remote connections. All of them use the ComputerName switch. To show how this switch works, see the following example; a command to create a new VM is being used to create a VM on a remote computer named HVHost.

New-VM –Name VM01 –ComputerName HVHost

To identify which commands support the Computername switch, you saw the Get-Command being used with a filter to find all the commandlets. After these steps, your servers will be ready to receive and create remote connections through PowerShell.

Question: 12 steps to remotely manage hyper-v server 2012 core

Here are 12 steps to remotely manage Hyper-V Server 2012 Core. Have you setup a Microsoft Hyper-V Server 2012 Core edition and now you want to remotely manage it in a workgroup (non-domain) environment?

Hopefully I can help ease your frustration with this article by showing you what worked for me.

If Microsoft did one thing that really tested my patients it’s trying to remotely manage Hyper-V Server Core in a workgroup environment.

Not long ago, I wrote an article titled Remotely Mange Hyper-V Server 2012 Core but admit I lost steam with wanting to work with it after that article/video. I wasn’t very confident with those instructions because every time I tested it there seemed to be different results.

Earlier today I decided to tackle this one again because I have had a lot of questions on this topic. It appears a lot of you out there are having similar issues. I feel very confident this time that I have all the instructions tested and working.

12 Steps to Remotely Manage Hyper-V

Quick run-down

  • Server: Microsoft Hyper-V Server 2012 Core (Free Edition)
  • Client: Windows 8 Pro

This next section is what I’m calling the condensed (advanced) version.

Condensed (advanced) Version

Install Hyper-V Server 2012 Core and log in to the console.

  1. Configure date and time (select #9).
  2. Enable Remote Desktop (select #7). Also select the ‘Less Secure’ option.
  3. Configure Remote Management (select #4 then #1).
  4. Add local administrator account (select #3). Username and password need to be exactly the same as the account you are going to use on the client computer to manage this Hyper-V Server.
  5. Configure network settings (select #8). Configure as a static IP. Same subnet as your home network. Don’t forget to configure the DNS IP.
  6. Set the computer name (select #2). Rename the server and reboot.
  7. Remote Desktop to server. On your client machine, remote to the server via the IP address you assigned it. Use the credentials of the local administrator account you created earlier.
  8. Launch PowerShell. In the black cmd window, run the following command: start powershell
  9. Run the following commands:
    • Enable-NetFirewallRule -DisplayGroup “Windows Remote Management”
    • Enable-NetFirewallRule -DisplayGroup “Remote Event Log Management”
    • Enable-NetFirewallRule -DisplayGroup “Remote Volume Management”
    • Set-Service VDS -StartupType Automatic
  10. Reboot the server (select #12).
  11. Enable Client Firewall Rule. On your client machine, launch an elevated PowerShell prompt and type the following command:
    • Enable-NetFirewallRule -DisplayGroup “Remote Volume Management”
    • ii c:\windows\system32\drivers\etc
  12. Add server hostname and IP to hosts file. Right click hosts and select properties. In the security tab, add your username. Give your account modify rights.This is needed because some remote management tools we need to use rely on the hosts file to resolve the name. Without doing this you are highly likely to encounter some errors while trying to create VHDs and such. Error you might see: There was an unexpected error in configuring the hard disk.

There you have it: 12 steps to remotely manage Hyper-V Server 2012 Core.

You should now be able to remotely manage the Hyper-V server from the client machine. This includes managing the Hyper-V server’s disk from within the disk management console on the client. You should be able to create VHD’s successfully as well from within Hyper-V Manager on the client (assuming you installed the feature).

This was a quick tutorial on how to setup a working Hyper-V Server 2012 Core edition in a non-domain (workgroup) environment and still be able to remotely manage it.