Tag Archives: powershell

How is the future of PowerShell shaping up?

Now that PowerShell is no longer just for Windows — and is an open source project — what are the long-term implications of these changes?

Microsoft technical fellow Jeffrey Snover developed Windows PowerShell based on the parameters in his “Monad Manifesto.” If you compare his document to the various releases of Windows PowerShell, you’ll see Microsoft produced a majority of Snover’s vision. But, now that this systems administration tool is an open source project, what does this mean for the future of PowerShell?

I’ve used PowerShell for more than 12 years and arguably have as good an understanding of PowerShell as anyone. I don’t know, or understand, where PowerShell is going, so I suspect that many of its users are also confused.

When Microsoft announced that PowerShell would expand to the Linux and macOS platforms, the company said it would continue to support Windows PowerShell, but would not develop new features for the product. Let’s look at some of the recent changes to PowerShell and where the challenges lie.

Using different PowerShell versions

While it’s not directly related to PowerShell Core being open source, one benefit is the ability to install different PowerShell versions side by side. I currently have Windows PowerShell v5.1, PowerShell Core v6.0.1 and PowerShell Core v6.1 preview 2 installed on the same machine. I can test code across all three versions using the appropriate console or Visual Studio Code.

PowerShell versions
One benefit of the open source move is Windows PowerShell v5.1, PowerShell Core v6.0.1 and PowerShell Core v6.1 preview 2 can run on the same machine.

How admins benefit from open source PowerShell

The good points of the recent changes to PowerShell include access to the open source project, a faster release cadence and community input.

Another point in favor of PowerShell’s move is that you can see the code. If you can read C#, you can use that skill to track down and report on bugs you encounter. If you have a fix for the problem, then you can submit it.

Studying the code can give you insight into how PowerShell works. What it won’t explain is why PowerShell works the way it does. Previously, Microsoft MVPs and very few other people had access to Windows PowerShell code, but with the PowerShell Core code now available to more people, it can only make it a better product in the long run.

The PowerShell team expects to deliver a new release approximately every six months. The team released PowerShell v6.0 in January 2018. At the time of this article’s publication, version 6.1 is in its third preview release, with the final version expected soon. If the team maintains this release cadence, you can expect v6.2 in late 2018 or early 2019.

A faster release cadence implies quicker resolution of bugs and new features on a more regular basis. The downside to a faster release cadence is that you’ll have to keep upgrading your PowerShell instances to get the bug fixes and new features.

Of the Microsoft product teams, the Windows PowerShell team is one of the most accessible. They’ve been very active in the PowerShell community since the PowerShell v1 beta releases by engaging with users and incorporating their feedback. The scope of that dialog has expanded; anyone can report bug fixes or request new features.

The downside is the expectation that the originator of the request is expected to implement the changes. If you follow the project, you’ll see there are just a handful of community members who are heavily active.

Shortcomings of the PowerShell Core project

This leads us to the disadvantages now that PowerShell is an open-source project. In my view, the problems are:

  • it’s an open source project;
  • there’s no overarching vision for the project;
  • the user community lacks an understanding of what’s happening with PowerShell; and
  • gaps in the functionality.

[embedded content]

PowerShell’s inventor gives a status update on the automation tool

These points aren’t necessarily problems, but they are issues that could impact the PowerShell project in the long term.

Changing this vital automation and change management tool to an open source project has profound implications for the future of PowerShell. The PowerShell Core committee is the primary caretaker of PowerShell. This board has the final say on which proposals for new features will proceed.

At this point in time, the committee members are PowerShell team members. A number of them, including the original language design team, have worked on PowerShell from the start. If that level of knowledge is diluted, it could have an adverse effect on PowerShell.

The PowerShell project page supplies a number of short- to medium-term goals, but I haven’t seen a long-term plan that lays out the future of PowerShell. So far, the effort appears concentrated on porting the PowerShell engine to other platforms. If the only goal is to move PowerShell to a cross-platform administration tool, then more effort should go into bringing the current Windows PowerShell functionality to the other platforms.

Giving the PowerShell community a way to participate in the development of PowerShell is both a strength and a weakness. Some of the proposals show many users don’t understand how PowerShell works.

Giving the PowerShell community a way to participate in the development of PowerShell is both a strength and a weakness. Some of the proposals show many users don’t understand how PowerShell works. There are requests to make PowerShell more like Bash or other shells.

Other proposals seek to change how PowerShell works, which could break existing functionality. The PowerShell committee has done a good job of managing the more controversial proposals, but clearing up long-term goals for the project would reduce requests that don’t fit into the future of PowerShell.

The project is also addressing gaps in functionality. Many of the current Windows PowerShell v5.1 modules will work in PowerShell Core. At the PowerShell + DevOps Global Summit 2018, one demonstration showed how to use implicit remoting to access Windows PowerShell v5.1 modules on the local machine through PowerShell Core v6. While not ideal, this method works until the module authors convert them to run in PowerShell Core.

One gap that needs work is the functionality on Linux and macOS systems. PowerShell Core is missing the cmdlets needed to perform standard administrative tasks, such as working with network adapters, storage, printer management, local accounts and groups.

Availability of the ConvertFrom-String cmdlet would be a huge boost by giving admins the ability to use native Linux commands then turn the output into objects for further processing in PowerShell. Unfortunately, ConvertFrom-String uses code that cannot be open sourced, so it’s not an option currently. Until this functionality gap gets closed, Linux and macOS will be second-class citizens in the PowerShell world.

Mind the feature gaps in the PowerShell open source project


Even though the current version of the PowerShell open source project lacks much of the functionality of Windows…

“;
}
});

/**
* remove unnecessary class from ul
*/
$(“#inlineregform”).find( “ul” ).removeClass(“default-list”);

/**
* Replace “errorMessageInput” class with “sign-up-error-msg” class
*/
function renameErrorMsgClass() {
$(“.errorMessageInput”).each(function() {
if ($(this).hasClass(“hidden”)) {
$(this).removeClass(“errorMessageInput hidden”).addClass(“sign-up-error-msg hidden”);
} else {
$(this).removeClass(“errorMessageInput”).addClass(“sign-up-error-msg”);
}
});
}

/**
* when validation function is called, replace “errorMessageInput” with “sign-up-error-msg”
* before return
*/
function validateThis(v, form) {
var validateReturn = urValidation.validate(v, form);
renameErrorMsgClass();
return validateReturn;
}

/**
* DoC pop-up window js – included in moScripts.js which is not included in responsive page
*/
$(“#inlineRegistration”).on(“click”,”a.consentWindow”, function(e) {
window.open(this.href, “Consent”, “width=500,height=600,scrollbars=1”);
e.preventDefault();
});

PowerShell, administrators can close those gaps with a few adjustments.

Microsoft released the first version of its cross-platform, open source version of PowerShell in January 2018. This version, officially called PowerShell Core 6.0, is not a straight swap for Windows PowerShell 5.1, even though it’s forked from the 5.1 code base and adapted for use on Windows, many Linux distributions and macOS.

The key difference is Windows PowerShell 5.1 and earlier versions run on the full .NET Framework for Windows, whereas the PowerShell open source project relies on .NET Core, which does not have access to the same .NET classes.

Differences between Windows PowerShell and PowerShell Core

Many PowerShell 5.1 features aren’t available in PowerShell Core 6, including the Integrated Scripting Environment (ISE), PowerShell workflows, Windows Management Instrumentation (WMI) cmdlets, event log cmdlets, performance counter cmdlets and the Pester module.

The large collection of PowerShell modules that work with Windows PowerShell are not available in PowerShell Core 6. Any binary PowerShell module compiled against the full .NET Framework won’t work in the PowerShell open source project, including the Active Directory module and the Exchange module.

The large collection of PowerShell modules that work with Windows PowerShell are not available in PowerShell Core 6.

PowerShell Core 6 brings some useful features. The first is the ability to administer Linux and macOS systems using PowerShell. The depth of cmdlets for Windows systems is not available on the non-Windows platforms, but the PowerShell community might fill those holes through the PowerShell Gallery.

Secondly, PowerShell 6 introduced remoting over Secure Socket Shell (SSH) as opposed to remoting with the Web Services-Management protocol. This enables remoting to and from Linux systems and provides an easy way to remote to and from non-domain Windows machines.

Installing and configuring SSH on Windows is getting easier, and the inclusion of SSH as an optional feature in the latest Windows 10 and Windows Server previews will hopefully lead to a simpler remoting installation and configuration process.

How to surmount functionality obstacles

You can overcome some of the missing features in PowerShell Core 6, starting with the ISE. Use Visual Studio (VS) Code instead of ISE for developing scripts. VS Code is an open source editor that runs on Windows, Linux and macOS. VS Code uses Windows PowerShell or PowerShell Core in the integrated terminal if both are installed.

PowerShell workflows, which allow functions to run on several machines at the same time, are never going to be a part of PowerShell Core because this feature is difficult to implement. Instead, you can use PowerShell runspaces to provide parallel processing. While they aren’t easy to code, a proposal exists to create cmdlets for managing runspaces.

An example of a simple PowerShell workflow is:

workflow test1 {

  parallel {

    Get-CimInstance -ClassName Win32_OperatingSystem

    Get-CimInstance -ClassName Win32_ComputerSystem

  }

}

test1

Figure 1 shows the results of this script.

PowerShell workflow
Figure 1. Running a workflow on Windows PowerShell 5.1 in the PowerShell Integrated Scripting Environment

Emulating a PowerShell workflow with runspaces results in the following code:

## create runspace pool with min =1 and max = 5 runspaces
$rp = [runspacefactory]::CreateRunspacePool(1,5)
## create powershell and link to runspace pool
$ps = [powershell]::Create()
$ps.RunspacePool = $rp
$rp.Open()
$cmds = New-Object -TypeName System.Collections.ArrayList

1..2 | ForEach-Object {
    $psa = [powershell]::Create()
    $psa.RunspacePool = $rp
    if ($_ -eq 1) {
       [void]$psa.AddScript({
         Get-CimInstance -ClassName Win32_OperatingSystem
       })
    } else {
        [void]$psa.AddScript({
            Get-CimInstance -ClassName Win32_ComputerSystem
          })
    }
$handle = $psa.BeginInvoke()
     $temp = ” | Select-Object PowerShell, Handle
     $temp.PowerShell = $psa
     $temp.Handle = $handle
     [void]$cmds.Add($temp)
}

 

## view progress
$cmds | Select-Object -ExpandProperty handle
## retrieve data
$cmds | ForEach-Object {$_.PowerShell.EndInvoke($_.Handle)}

## clean up
$cmds | ForEach-Object {$_.PowerShell.Dispose()} 
$rp.Close()
$rp.Dispose()

Figure 2 shows this code running on PowerShell Core 6 in the VS Code editor.

PowerShell runspaces in VS Code
Figure 2. Executing code with runspaces in PowerShell Core 6 in the VS Code editor.

Runspaces code works in Windows PowerShell 5.1 and PowerShell Core 6. Administrators can also simplify runspaces with the PoshRSjob module from the PowerShell Gallery. The latest version works in PowerShell Core 6 on Linux and Windows.

The developers of the PowerShell open source project plan to add missing WMI, event log and performance cmdlets into the Windows Compatibility Pack for .NET Core. WMI cmdlets are effectively deprecated in favor of the Common Information Model (CIM) cmdlets, which are available in PowerShell Core 6 and Windows PowerShell 3 and newer.

[embedded content]

Showing PowerShell Core’s cross-platform
capabilities

Event log cmdlets only work with the traditional event logs. If you need to work with the new style application and service logs, you have to use the Get-WinEvent cmdlet, which also works with the old-style logs.

The following command uses the older Get-EventLog cmdlet:

Get-EventLog -LogName System -Newest 5

It’s easy enough to switch to the Get-WinEvent cmdlet to get similar results:

Get-WinEvent -LogName System -MaxEvents 5

The Get-WinEvent cmdlet can’t clear, limit, write to or create/remove classic event logs, but you can configure event logs using the properties and methods on the objects returned.

Get-WinEvent -ListLog *

In Windows PowerShell 5.1, you can run the following command to access performance counters:

Get-Counter -Counter ‘Processor(*)% Processor Time’

This generates the following output:

Timestamp                 CounterSamples

———                 ————–

31/03/2018 15:18:34       \w510w10processor(0)% processor time :

                          1.56703775955929

 

                          \w510w10processor(1)% processor time :

                          0.00460978748879626

 

                          \w510w10processor(2)% processor time :

                          1.56703775955929

 

                          \w510w10processor(3)% processor time :

                          0.00460978748879626

 

                          \w510w10processor(4)% processor time :

                          0.00460978748879626

 

                          \w510w10processor(5)% processor time :

                          4.69189370370026

 

                          \w510w10processor(6)% processor time :

                          3.12946573162978

 

                          \w510w10processor(7)% processor time :

                          0.00460978748879626

 

                          \w510w10processor(_total)% processor time :

                          1.37173676293523

The alternative way to return performance counter data is with CIM classes, which work in Windows PowerShell 5.1 and PowerShell Core 6:

Get-CimInstance -ClassName Win32_PerfFormattedData_PerfOS_Processor | select Name, PercentProcessorTime

 

Name   PercentProcessorTime

—-   ——————–

_Total                   13

0                        50

1                         0

2                         0

3                        43

4                         6

5                         6

6                         0

7                         0

PowerShell Core 6 can access many of the older PowerShell modules, such as the networking or storage modules, available on Windows 8 or Windows Server 2012. To do this, add the following entry in your profile to the Windows PowerShell 5.1 modules folder:

$env:PSModulePath =  $env:PSModulePath + ;C:WindowsSystem32WindowsPowerShellv1.0Modules’

Another way to do this is to import the module directly.

Import-Module C:WindowsSystem32WindowsPowerShellv1.0ModulesNetAdapterNetAdapter.psd1

Get-NetAdapter

 

Name                      ifIndex Status       MacAddress             LinkSpeed

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

vEthernet (nat)           16 Up           00-15-5D-82-CF-92        10 Gbps

vEthernet (DockerNAT)     20 Up           00-15-5D-36-C9-37        10 Gbps

vEthernet (Default Swi…  9 Up           2E-15-00-2B-41-72        10 Gbps

vEthernet (Wireless)      22 Up           F0-7B-CB-A4-30-9C     144.5 Mbps

vEthernet (LAN)           12 Up           00-15-5D-36-C9-11        10 Gbps

Network Bridge            24 Up           F0-7B-CB-A4-30-9C     144.5 Mbps

LAN                       14 Disconnected F0-DE-F1-00-3F-67          0 bps

Wireless                   8 Up           F0-7B-CB-A4-30-9C     144.5 Mbps

In the case of binary modules, such as Active Directory, you’ll have to revert to scripting when using the PowerShell open source version. If you want to administer Linux machines using PowerShell Core 6, you’ll have to do a lot of scripting or wait for the community to create the functionality.

Mastering PowerShell commands for Exchange by the book

The key to manage Exchange Server 2016 is to master PowerShell commands for Exchange.

With this latest version of Exchange, IT administrators must learn how to manage Exchange 2016 mailbox and client access and troubleshoot issues with the edge transport server, which routes email online and protects the system from malware and spam. Part of the difficulty of managing Exchange Server is learning how to use PowerShell, as the web-based Exchange admin center cannot handle every issue.

The book Practical PowerShell Exchange Server 2016: Second Edition by Damian Scoles and Dave Stork, teaches administrators with little PowerShell experience how to use the scripting language to ease configuration jobs or handle tasks with automation.

For experienced PowerShell users, this book shares ways to improve existing scripts. Administrators can learn how to use PowerShell commands for Exchange to customize their servers, manage mailboxes and mobile devices, and create reports.

From migrating to Exchange 2016 to taking advantage of its new functions, this book walks administrators through common tasks with PowerShell commands for Exchange.

From migrating to Exchange 2016 to taking advantage of its new functions, this book walks administrators through common tasks with PowerShell commands for Exchange. This excerpt from chapter 14 explains why mailbox migrations work better with PowerShell commands for Exchange:

It’s very unlikely that there is no Exchange admin that has not or will not have to move one or more mailboxes from one Exchange database to another. While some scenarios are quite easy, there are some scenarios that require some more planning, reporting and so on.

With the introduction of Exchange 2010, Microsoft also improved the one element that would grow into an almost impossible task: Mailbox moves. The revolutionary change in Exchange 2010 made it possible to move mailbox data while the user still could access and modify his/her data: Online Mailbox Move. New incoming mail is queued in mail queues until the mailbox is available again (i.e. when it’s successfully moved or has failed).

Practical PowerShell Exchange Server 2016

With the trend of growing average mailbox sizes, this was a necessary step. Otherwise it could mean that a migration would take too long to perform in a single big bang, meaning that you have to migrate mailboxes in stages and maintain a coexistence environment until the last mailbox has been moved. It was also a major step towards making Office 365 more accessible to migrate to and more flexible for Microsoft on managing servers and databases. Just consider moving mailboxes like in Exchange 2003, hoping that every mailbox has moved before your maintenance window closes… .

Luckily this has changed, and as Exchange 2016 can only coexist with Exchange 2010 and 2013, earlier versions of Exchange won’t be an issue. However, the option is still there with the -ForceOffline switch in the New-MoveRequest cmdlet. You shouldn’t have to use it under normal conditions, however from time to time a mailbox is fickle and can only move via an Offline move.

Now, most of the move mailbox options are available from within the Exchange Admin Center in one way or another. But in our experience, EAC is probably fine for simple migrations or the incidental move of one mailbox. If you migrate your server environment from one major build to another, it’s almost impossible to ignore PowerShell. Those migrations are far more complex and full of caveats, that it mostly always requires the use of custom PowerShell cmdlets and scripts

Editor’s note: This excerpt is from Practical PowerShell Exchange Server 2016: Second Edition, authored by Damian Scoles and Dave Stork, published by Practical PowerShell Press, 2017.

Will PowerShell Core 6 fill in missing features?

Administrators who have embraced PowerShell to automate tasks and manage systems will need to prepare themselves…

“;
}
});

/**
* remove unnecessary class from ul
*/
$(“#inlineregform”).find( “ul” ).removeClass(“default-list”);

/**
* Replace “errorMessageInput” class with “sign-up-error-msg” class
*/
function renameErrorMsgClass() {
$(“.errorMessageInput”).each(function() {
if ($(this).hasClass(“hidden”)) {
$(this).removeClass(“errorMessageInput hidden”).addClass(“sign-up-error-msg hidden”);
} else {
$(this).removeClass(“errorMessageInput”).addClass(“sign-up-error-msg”);
}
});
}

/**
* when validation function is called, replace “errorMessageInput” with “sign-up-error-msg”
* before return
*/
function validateThis(v, form) {
var validateReturn = urValidation.validate(v, form);
renameErrorMsgClass();
return validateReturn;
}

/**
* DoC pop-up window js – included in moScripts.js which is not included in responsive page
*/
$(“#inlineRegistration”).on(“click”,”a.consentWindow”, function(e) {
window.open(this.href, “Consent”, “width=500,height=600,scrollbars=1”);
e.preventDefault();
});

as Microsoft plans to focus its energies in the open source version called PowerShell Core.

All signs from Microsoft indicate it is heading away from the Windows-only version of PowerShell, which the company said it will continue to support with critical fixes — but no further upgrades. The company plans to release PowerShell Core 6 shortly. Here’s what admins need to know about the transition.

What’s different with PowerShell Core?

PowerShell Core 6 is an open source configuration management and automation tool from Microsoft. As of this article’s publication, Microsoft made a release candidate available in November. PowerShell Core 6 represents a significant change for administrators because it shifts from a Windows-only platform to accommodate heterogeneous IT shops and hybrid cloud networks. Microsoft’s intention is to give administrative teams a single tool to manage Linux, macOS and Windows systems.

What features are not in PowerShell Core?

PowerShell Core runs on .NET Core and uses .NET Standard 2.0, the latter is a common library that helps make some current Windows PowerShell modules work in PowerShell Core.

As a subset of the .NET Framework, PowerShell Core misses out on some useful features in Windows PowerShell. For example, workflow enables admins to execute tasks or retrieve data through a sequence of automated steps. This feature is not in PowerShell Core 6. Similarly, tasks such as sequencing, checkpointing, resumability and persistence are not available in PowerShell Core.

A few other features missing from PowerShell Core 6 are:

  • Windows Presentation Foundation: This is the group of .NET libraries that enable coders to build UIs for scripts. It offers a common platform for developers and designers to work together with standard tools to create Windows and web interfaces.
  • Windows Forms: In PowerShell 5.0 for Windows, the Windows Forms feature provides a robust platform to build rich client apps with the GUI class library on the .NET Framework. To create a form, the admin loads the System.Windows.Forms assembly, creates a new object of type system.windows.forms and calls the ShowDialog method. With PowerShell Core 6, administrators lose this capability.
  • Cmdlets: As of publication, most cmdlets in Windows PowerShell have not been ported to PowerShell Core 6. However, the compatibility with .NET assemblies enables admins to use the existing modules. Users on Linux are limited to modules mostly related to security, management and utility. Admins on that platform can use the PowerShellGet in-box module to install, update and discover PowerShell modules. PowerShell Web Access is not available for non-Windows systems because it requires Internet Information Services, the Windows-based web server functionality.
  • PowerShell remoting: Microsoft ports Secure Socket Shell to Windows, and SSH is already popular in other environments. That means SSH-based remoting for PowerShell is likely the best option for remoting tasks. Modules such as Hyper-V, Storage, NetTCPIP and DnsClient have not been ported to PowerShell Core 6, but Microsoft plans to add them.

Is there a new scripting environment?

For Windows administrators, the PowerShell Integrated Scripting Environment (ISE) is a handy editor that admins use to write, test and debug commands to manage networks. But PowerShell ISE is not included in PowerShell Core 6, so administrators must move to a different integrated development environment.

Microsoft recommends admins use Visual Studio Code (VS Code). VS Code is a cross-platform tool and uses web technologies to provide a rich editing experience across many languages. However, VS Code lacks some of PowerShell ISE’s features, such as PSEdit and remote tabs. PSEdit enables admins to edit files on remote systems without leaving the development environment. Despite VS Code’s limitations, Windows admins should plan to migrate from PowerShell ISE and familiarize themselves with VS Code.

What about Desired State Configuration?

Microsoft offers two versions of Desired State Configuration: Windows PowerShell DSC and DSC for Linux. DSC helps administrators maintain control over software deployments and servers to avoid configuration drift.

Microsoft plans to combine these two options into a single cross-platform version called DSC Core, which will require PowerShell Core and .NET Core. DSC Core is not dependent on Windows Management Framework (WMF) and Windows Management Instrumentation (WMI) and is compatible with Windows PowerShell DSC. It supports resources written in Python, C and C++.

Debugging in DSC has always been troublesome, and ISE eased that process. But with Microsoft phasing out ISE, what should admins do now? A Microsoft blog says the company uses VS Code internally for DSC resource development and plans to release instructional videos that explain how to use the PowerShell extension for DSC resource development.

PowerShell Core 6 is still in its infancy, but Microsoft’s moves show the company will forge ahead with its plan to replace Windows PowerShell. This change brings a significant overhaul to the PowerShell landscape, and IT admins who depend on this automation tool should pay close attention to news related to its development.

Dig Deeper on Microsoft Windows Scripting Language

Use the Azure Custom Script Extension for your Azure VMs

It’s easy to execute custom scripts — including PowerShell scripts — in a VM running in on-premises Hyper-V hosts….

“;
}
});

/**
* remove unnecessary class from ul
*/
$(“#inlineregform”).find( “ul” ).removeClass(“default-list”);

/**
* Replace “errorMessageInput” class with “sign-up-error-msg” class
*/
function renameErrorMsgClass() {
$(“.errorMessageInput”).each(function() {
if ($(this).hasClass(“hidden”)) {
$(this).removeClass(“errorMessageInput hidden”).addClass(“sign-up-error-msg hidden”);
} else {
$(this).removeClass(“errorMessageInput”).addClass(“sign-up-error-msg”);
}
});
}

/**
* when validation function is called, replace “errorMessageInput” with “sign-up-error-msg”
* before return
*/
function validateThis(v, form) {
var validateReturn = urValidation.validate(v, form);
renameErrorMsgClass();
return validateReturn;
}

/**
* DoC pop-up window js – included in moScripts.js which is not included in responsive page
*/
$(“#inlineRegistration”).on(“click”,”a.consentWindow”, function(e) {
window.open(this.href, “Consent”, “width=500,height=600,scrollbars=1”);
e.preventDefault();
});

All you need to do is create a script that the destination VM can support and then run it via PowerShell Direct or copy the script to the VM. Azure also supports executing custom scripts in Azure VMs, but the way you execute them is slightly different.

Azure Custom Script Extension is a plug-in designed to only work with Azure VMs. It can be used to execute scripts stored in an Azure blob container or in a valid URL that’s accessible by Azure Portal and PowerShell command lines. Before you execute scripts inside Azure VMs, you’ll be required to decide the source of the script and resource group name in which the Azure VM is located. If your script is stored in an Azure blob container, you’ll be required to supply the storage account name, storage account key and blob container where the script is located. By executing the command below, you’re executing a script stored in an Azure blob container named VMScripts:

Set-AzureRMVMCustomScriptExtension –ResourceGroupName “RSGroup1” –Location “Central US” –VMName “SQLVM” -StorageAccountName “StorageAccount1” –StorageAccountKey {StorageAccountKeyHere} –FileName “ThisScript.PS1” –ContainerName “VMScripts”

If you have a script available in other locations, such as GitHub, you’ll be required to download the script from GitHub to the Azure VM as it’s shown in the command below:

Set-AzureRMVMCustomScriptExtension –ResourceGroupName “RSGroup1” –VMName “SQLVM” –Name “VMScripts” –FileURI {Complete Script Path here} –Run “ScriptFile.PS1” –Location “Central US”

Azure Custom Script Extension is available for both Azure Windows and Linux VMs. You can execute any PowerShell script in Azure Windows VMs and any Bash scripts in Azure Linux VMs.

Troubleshooting issues

If you face any issues during execution of the scripts, you might want to check execution logs found under C:WindowsAzureLogsPlugins
Microsoft.Compute.CustomScriptExtension in Azure VMs. If the script failed to execute, make sure the script was downloaded to Azure VMs from either a storage blob container or URL. Scripts are downloaded to the C:
PackagesPluginsMicrosoft.Compute.CustomScriptExtension1.*Downloads location in the Azure VM.

You might want to execute custom scripts using Azure Custom Script Extension to support post-deployment configurations, such as configuring OS settings and installing line-of-business applications.

Next Steps

Learn more about Azure Security Center

Solve API problems in Azure

Avoid downtime with Azure availability sets

Dig Deeper on Cloud computing architecture

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever’s puzzling you.

Tools for system administrators that don’t cost a dime

Windows admins can’t solve every problem with System Center or PowerShell. There are times when a simple utility…

“;
}
});

/**
* remove unnecessary class from ul
*/
$(“#inlineregform”).find( “ul” ).removeClass(“default-list”);

/**
* Replace “errorMessageInput” class with “sign-up-error-msg” class
*/
function renameErrorMsgClass() {
$(“.errorMessageInput”).each(function() {
if ($(this).hasClass(“hidden”)) {
$(this).removeClass(“errorMessageInput hidden”).addClass(“sign-up-error-msg hidden”);
} else {
$(this).removeClass(“errorMessageInput”).addClass(“sign-up-error-msg”);
}
});
}

/**
* when validation function is called, replace “errorMessageInput” with “sign-up-error-msg”
* before return
*/
function validateThis(v, form) {
var validateReturn = urValidation.validate(v, form);
renameErrorMsgClass();
return validateReturn;
}

/**
* DoC pop-up window js – included in moScripts.js which is not included in responsive page
*/
$(“#inlineRegistration”).on(“click”,”a.consentWindow”, function(e) {
window.open(this.href, “Consent”, “width=500,height=600,scrollbars=1”);
e.preventDefault();
});

fills a particular need to assist a troubleshooting exercise or just make a daily task easier.

A system administrator handles a number of small tasks on a daily basis. They must often create screenshots for documentation or to pass along to the help desk to help illustrate an issue. There are many freeware utilities available that make the IT staff more productive. These helpful free tools for system administrators are worth a look.

Check on disk space use

Windows Explorer and PowerShell are fine for general file management, but some tools for system administrators offer more functionality than native software. Dirsize and SpaceSniffer are two freeware applications that give a quick overview of what takes up space on the disk. These utilities are portable on Windows, which provides additional flexibility.

Windows Explorer and PowerShell are fine for general file management, but some tools for system administrators offer more functionality than native software.

Dirsize: This is the more basic application. It provides a File Explorer tree view and shows the size of each folder. Admins can adjust the color coding to their preference; the default settings highlight folders with less data in green, while folders that take up more space show up as red.

SpaceSniffer: A more advanced tool for system administrators, SpaceSniffer offers a visual representation of boxes to show what folders and files use large amounts of space. These boxes are also layered to show the location of data within a specific folder. Admins cut or delete unwanted data from the application with a right click on a file or folder.

Capture screenshots in a snap

The native PrintScreen or Alt+PrtScr hotkey in Windows saves the entire screen or active window, respectively, to the clipboard. The Snipping Tool, which debuted in Windows Vista, selects a specific part of the screen for a screenshot. But there are even better free tools for system administrators for this purpose.

Greenshot: This tool runs in the background and uses both the PrintScreen option and combinations of the Alt, Shift and Ctrl keys to grab certain parts or the entire screen based on preferences. Configure the different commands to capture full screen, window, region, last region and a scrolling window in Internet Explorer. Greenshot also configures apps that automatically open screenshots, such as MS Paint or GreenShot’s own editor, to highlight areas and add comments to the image. Admins then have several options, such as sending the screenshot to a printer or adding it to an email message. This is a useful tool for system administrators who take many screenshots to share information and get technical support. Greenshot also has a portable version.

ShareX: This utility is more feature-rich than Greenshot with its greater customization options and optical character recognition. ShareX also provides more upload locations. Some admins should look at this setting first since screenshots go to the Imgur image-sharing site by default. ShareX stores the Imgur URLs to share the full image, its thumbnail and the link to delete the image from the site. Users can automatically upload the screenshot to most major social media platforms, create a thumbnail of the image or choose from a wide range of other options. ShareX is the ideal freeware screenshot choice for advanced users, while Greenshot suits those with simpler needs.

Manipulate and store text

The Notepad and WordPad text editors are adequate for simple text handling, but there are several freeware utilities that make it easier for admins to type and store text.

Notepad++: This application touts a wide array of features. It numbers and highlights lines of text, allows tabbed documents and generates syntax highlighting for numerous languages, such as JavaScript, PowerShell and extensible markup language.

Another advanced feature is macro recording, which is useful when search and replace is insufficient. For example, a user who wants to remove a trailing space off the end of each line can use the feature to record the End+Backspace+Down Arrow key combination and play it back for each line in the file. This just scratches the surface of the capabilities in Notepad++.

Ditto: This tool is a way to overcome the inherent limits in the Windows clipboard. For example, if the admin copies text with Ctrl+C but doesn’t paste the content into a document or email, it invariably gets overwritten when the admin copies more text.

Ditto stores text and images copied to the clipboard, which admins can refer to at any time. The Ctrl+~ hotkey brings up the list of cached clipboard entries. The admin then chooses which item to paste. The program includes a setting to share clipboard entries to different computers. Admins who constantly copy and paste into the clipboard will appreciate the other features in this highly configurable application.

Gain remote control of servers

Windows admins spend a majority of their time on computers that are not physically near them. But sometimes they must manage multiple computers that are all within an arm’s length. Microsoft offers a different freeware option that works in each scenario.

Remote Desktop Connection Manager (RDCMan): This Microsoft tool gives Windows administrators a single management console to select and then connect to a remote server. Admins don’t need to memorize every server name and click on the right one. In RDCMan, each server can have its own remote desktop settings, whereas the native Remote Desktop app in Windows only remembers the last settings used. RDCMan produces a thumbnail view to show all the servers in the list and displays what the desktop showed in the last session. Admins use RDCMan to configure multiple desktop sets so they can group servers to their preference.

Mouse without Borders: This virtual keyboard, video, mouse (KVM) switch from Microsoft enables admins to control up to four PCs at once from a single mouse and keyboard over the network. The client must run on each device, but this is a great option if there are multiple physical PCs and laptops on the admin’s desk. When the cursor moves off the edge of one monitor, it appears on the next computer. The admin can copy and paste files from one computer to the next, as well as key in commands from a single keyboard. Even if it’s only a two-PC setup of a user box and an admin box, Mouse without Borders is worth the cost compared to a physical KVM. There are two caveats: It requires space for multiple monitors and isn’t ideal if the hardware constantly changes.

Next Steps

Forget virtual desktop infrastructure — Remote Desktop Session Host is the future

Dual Monitor Tools tailored for multiple monitor users

Avoid falling into the IT automation money pit

Microsoft’s VS Code embrace prompts PowerShell editor debate

Windows admins who write scripts with PowerShell ISE must switch allegiances if Microsoft has its way.

Since 2009, Microsoft has positioned the PowerShell Integrated Scripting Environment (ISE) as the official PowerShell editor to develop and debug scripts on Windows. But Microsoft’s effort to steer Windows, Linux and macOS users to PowerShell Core as an all-encompassing management tool requires a script editor that works on all those systems.

In May 2017, Microsoft named a new official PowerShell editor: Visual Studio Code (VS Code), a free, open source editor with a PowerShell extension so admins on multiple platforms can build PowerShell scripts. Microsoft continues to support PowerShell ISE for now but plans to focus development efforts on VS Code.

For IT engineers who code in multiple languages, VS Code is the recommended tool. It’s also a better tool even for people who only write PowerShell scripts and modules, said Jeffery Hicks, IT author and trainer.

“It’s the future,” he said. “ISE will no longer get improvements; we’re not going to see updates to it. What we have now is what we’re always going to have. VS Code is going to be continually updated, and they’ll fix bugs.”

Microsoft continues to support PowerShell ISE for now but plans to focus development efforts on VS Code.

While VS Code might be the future of PowerShell development, not everyone thinks it’s ready for prime time.

Jeff Wilson, an IT admin based in Los Angeles who works in a Windows shop, experiments with VS Code to learn how it works but quickly noticed it lacked some of PowerShell ISE’s functionality. ISE uses default profiles to let Wilson access all his administrative sessions — such as Exchange Online, SharePoint and Hyper-V clusters — without delay.

“It’s a huge time-saver, and it’s really valuable to me,” he said. “It’s the famous single pane of glass because it’s so flexible. So with VS Code, when I installed it, I wanted to duplicate the experience I had with ISE. … It wasn’t immediately evident to me how I would do that. That’s problematic, but [at least] I still have ISE.”

Expect a bumpy transition to VS Code

PowerShell ISE veterans such as Wilson will need time to adapt to the different layout and terminology in VS Code.

Admins use the integrated PowerShell console in PowerShell ISE to access menu items and keyboard shortcuts. With the integrated console, admins see the output as they write scripts. The console in VS Code needs work, Hicks said.

“The PowerShell integrated terminal that is shipping in VS Code now is not quite as feature-complete as it is in the ISE,” he said. “It’s still a little buggy, and it doesn’t quite feel the way you want it to. I have muscle memory [from PowerShell ISE], so when I do presentations, I still typically use PowerShell ISE because I can toggle between the code and the presentation on the full screen. I can’t really do that in VS Code.”

Despite these shortcomings, Hicks recommends admins move to VS Code as their PowerShell editor for its integration with the Git code management system and ability to auto-format code to make it easier to read.

PowerShell Studio gives scripts a GUI

For IT pros who want more advanced features from a PowerShell editor, a commercial product such as PowerShell Studio is another option.

Wilson builds front ends to his scripts with PowerShell Studio for his company’s help desk workers who want a point-and-click UI.

PowerShell Studio, which is a Sapien product, is Windows only, although Sapien also offers iPowerShell, a pared-down and free tool that’s designed for Mac, Android and iOS users who write scripts remotely. Additionally, Sapien’s PrimalScript product is compatible with PowerShell Core.

For Hicks — a former Sapien employee — one of the editor’s big selling points is that it builds a GUI on a PowerShell script, which isn’t possible in PowerShell ISE or VS Code. Admins can also use PowerShell Studio to export scripts as executable files, easily create modules, build advanced functions with multiple parameters, and auto-generate comment-based help for existing functions.

Wilson writes longer scripts and complex functions in PowerShell Studio, which he calls a more fully thought-out developing environment than ISE or VS Code. It also features a way to add a layer of security to the finished script.

“I always sign my scripts with a digital certificate and [PowerShell Studio] makes it easier to do,” Wilson said.

There’s a cost to this feature richness; a one-year subscription to PowerShell Studio 2017 is $389.

“If you don’t need 90% of the features, maybe it’s not worth your time and money,” he said. “But if that one feature Sapien offers [in PowerShell Studio] saves you a lot of time and money, then it’s worth it.”

Dan Cagen is the associate site editor for SearchWindowsServer.com. Write to him at dcagen@techtarget.com.

Filter and query Windows event logs with PowerShell

In addition to its automation capabilities, PowerShell helps the IT staff troubleshoot problems with Windows, specifically…

“;
}
});

/**
* remove unnecessary class from ul
*/
$(“#inlineregform”).find( “ul” ).removeClass(“default-list”);

/**
* Replace “errorMessageInput” class with “sign-up-error-msg” class
*/
function renameErrorMsgClass() {
$(“.errorMessageInput”).each(function() {
if ($(this).hasClass(“hidden”)) {
$(this).removeClass(“errorMessageInput hidden”).addClass(“sign-up-error-msg hidden”);
} else {
$(this).removeClass(“errorMessageInput”).addClass(“sign-up-error-msg”);
}
});
}

/**
* when validation function is called, replace “errorMessageInput” with “sign-up-error-msg”
* before return
*/
function validateThis(v, form) {
var validateReturn = urValidation.validate(v, form);
renameErrorMsgClass();
return validateReturn;
}

/**
* DoC pop-up window js – included in moScripts.js which is not included in responsive page
*/
$(“#inlineRegistration”).on(“click”,”a.consentWindow”, function(e) {
window.open(this.href, “Consent”, “width=500,height=600,scrollbars=1”);
e.preventDefault();
});

when they need to find errors in the Windows event logs. PowerShell parses logs and has a few more advantages over the numerous third-party tools at administrators’ disposal. Microsoft includes PowerShell for free with Windows, which gives it a cost advantage over other vendors’ products. Also, PowerShell connects deeply with the OS to provide many options to filter logs and query across multiple systems simultaneously.

Get-EventLog is the primary cmdlet administrators utilize to manage Windows event logs. This cmdlet shows the log’s contents with the -LogName parameter, followed by the name of the desired log file.

Log files can get large, but this cmdlet cuts results down to more easily reveal relevant events.

Use this command to show a summary of available log files:

Get-EventLog -List

PowerShell returns the log names and the number of events in each. Let’s focus on the Application log, which can contain several thousand entries. This command displays the Application log events:

Get-EventLog -LogName “Application”

The command output shows the log file’s full contents, which is not helpful. To filter the results, use this example to show the 10 most recent entries:

Get-EventLog -LogName “Application” -Newest 10

Next, take the command a step further, and find the 10 most recent errors with the -EntryType parameter:

Get-EventLog -LogName “Application” -EntryType “Error” -Newest 10

PowerShell also finds specific error occurrences. Find the 10 most recent instances of event 7670 — an issue related to SQL Server database access — with this command:

Get-EventLog -LogName “Application” -Index 7670 -Newest 10

Event 7670 often accompanies several other SQL Server events, such as 7671 or 7673. PowerShell specifies a range of event IDs rather than a single event ID. Let’s say you’re interested in event IDs 7670, 7671, 7672 and 7673. Use this command to view the 10 most recent SQL Server-related errors with those event IDs in the Application log:

Get-EventLog -LogName “Application” -Index(7670..7673) -Newest 10

Alternatively, the command to list SQL errors — which varies based on the SQL Server version — resembles this:

Get-EventLog -LogName “Application” -EntryType “Error” -Source “SQLLocalDB 11.0” -Newest 10

How to check logs on remote machines

PowerShell also filters log events on Windows systems across the network. The administrator must specify the -ComputerName parameter, followed by the NetBIOS name, fully qualified domain name or the target system’s IP address.

To show results from several computers, store the computer names in a variable, and then use a ForEach loop. If the server names are Server1, Server2 and Server3, for example, use these commands to query each server:

$Computers=’Server1′,’Server2′,’Server3′

ForEach($Computer in $Computers){Get-EventLog -ComputerName $Computer -LogName “Application” -Newest 10}

The output does not list the name of the server with the event. To adjust this, customize the results: Append the pipe symbol, followed by the Select-Object cmdlet and the fields to display. The valid field names are EventID, MachineName, Data, Index, Category, CategoryNumber, EntryType, Message, Source, ReplacementStrings, InstanceID, TimeGenerated, TimeWritten, UserName, Site and Container.

[embedded content]

How to parse event log
message field with PowerShell

This command returns the server name, event ID, time and description:

$Computers=’Server1′,’Server2′,’Server3′

ForEach($Computer in $Computers){Get-EventLog -ComputerName $Computer -LogName “Application” -Newest 10} | Select-Object MachineName, EventID, TimeGenerated, Message

These are just a few methods to parse Windows event logs with Get-EventLog. Microsoft provides an extensive list of other ways this cmdlet helps administrators troubleshoot Windows systems.

Next Steps

PowerShell commands to troubleshoot Exchange Server

Implement PowerShell’s piping capabilities to build scripts

PowerShell Gallery offers easy access to scripts

Why Your Hyper-V PowerShell Commands Don’t Work (and how to fix them)

14 Sep 2017 by Eric Siron
   
0    
Hyper-V & PowerShell

I occasionally receive questions about Hyper-V-related PowerShell cmdlets not working as expected. Sometimes these problems arise with the module that Microsoft provides; other times, they manifest with third-party tools. Even my own tools show these symptoms. Most GUI tools are developed to avoid the problems that plague the command line, but the solutions aren’t always perfect.

The WMI Foundation

All tools, graphical or command-line, eventually work their way back to the only external interface that Hyper-V provides: its WIM/CIM provider. CIM stands for “Common Information Model”. The Distributed Management Task Force (DMTF) maintains the CIM standard. CIM defines a number of interfaces pertaining to management. Anyone can write CIM-conforming modules to work with their systems. These modules allow users, applications, and services to retrieve information and/or send commands to the managed system. By leveraging CIM, software and hardware manufacturers can provide APIs and controls with predictable, standardized behavior.

Traditionally, Microsoft has implemented CIM via Windows Management Instrumentation (WMI). Many WMI instructions involved VBS or WMIC. As PowerShell gained popularity, WMI also gained popularity due to the relative ease of Get-WmiObject. Depending on where you look in Microsoft’s vast documentation, you might see pushes away from the Microsoft-specific WMI implementation toward the more standard CIM corollaries. Get-CimInstance provides something of an analog to Get-WmiObject, but they are not interchangeable.

For any of this to ever make any sense, you need to understand one thing: anyone can write a WMI provider. The object definitions and syntax of a provider all descend from the common standard, but the provider’s developer determines how it all functions behind the scenes.

Why Hyper-V PowerShell Cmdlets May Not Work

Beyond minor things like incorrect syntax and environmental things like failed hardware, two common reasons cause prevent these tools from functioning as expected.

The Hyper-V Security Model

I told you all that about WMI so that this part would be easier to follow. The developers behind the Hyper-V WMI provider decide how it will react to any given WMI/CIM command that it receives. Sometimes, it chooses to have no reaction at all.

Before I go too far, I want to make it clear that no documentation exists for the security model in Hyper-V’s WMI provider. I ran into some issues some time ago with WMI commands not working the way that I expected. I opened a case with Microsoft, and it wound up going all the way to the developers. The answer that came back pointed to the internal coding of the module. In other words, I was experiencing a side effect of designed behavior. So, I asked if they would give me the documentation on that — basically, anything on what caused that behavior. I was told that it doesn’t exist. They obviously don’t have any externally-facing documentation, but they don’t have anything internal, either. So, everything that you’re going to see in this article originates from experienced (and repeatable) behavior. No insider secrets or pilfered knowledge were used in the creation of this material.

Seeing Effects of the Hyper-V Security Model in Action

Think about any “Get” PowerShell cmdlet. What happens when you run a “Get” against objects that don’t exist? For example, what happens when I run Get-Job when no jobs are present?

psnowork_emptygetjobNothing! That’s what happens. You get nothing.

So, if I run Get-VM and get nothing (2012/R2):

psnowork_emptygetvm

That means that the host has no virtual machines, right?

But wait:

Hyper-V Powershell commands help

What happened? A surprise Live Migration?

Look at the title bars carefully. The session on the left was started normally. The session on the right was started by using Run as administrator.

The PowerShell behavior has changed in 2016:

psnowork_emptygetvm2016

The PowerShell cmdlets that I tried now show an appropriate error message. However, only the PowerShell module has been changed. The WMI provider behaves as it always has:

psnowork_wmigetvm2016

To clarify that messy output, I ran
gwmi -Namespace rootvirtualizationv2 -Class Msvm_ComputerSystem -Filter ‘Caption=”Virtual Machine”‘ as a non-privileged user and the system gave no output. That window overlaps another window that contains the output from Get-VM in an elevated session.

Understanding the Effects of the Hyper-V Security Model

When we don’t have permissions to do something, we expect that the system will alert us. If we try to open a file, we get a helpful error message explaining why the system can’t allow it. We’ve all experienced that enough times that we’ve been trained to expect a red flag. The Hyper-V WMI provider does not exhibit that expected behavior. I have never attempted to program a WMI provider myself, so I don’t want to pass any judgment. I noticed that the MSCluster namespace acts the same way, so it may be something inherent to CIM/WMI that the provider authors have no control over.

In order for a WMI query to work against Hyper-V’s provider, you must be running with administrative privileges. Confusingly, “being a member of the Administrators group” and “running with administrative privileges” are not always the same thing. When working with the Hyper-V provider on the local system, you must always ensure that you run with elevated privileges (Run as administrator) — even if you log on with an administrative account. Remote processes don’t have that problem.

The administrative requirement presents another stumbling block: you cannot create a permanent WMI event watcher for anything in the Hyper-V provider. Permanent WMI registration operates anonymously; the Hyper-V provider requires confirmed administrative privileges. As with everything else, no errors are thrown. Permanent WMI watchers simply do not function.

The takeaway: when you unexpectedly get no output from a Hyper-V-related PowerShell command, you most likely do not have sufficient permissions. Because the behavior bubbles up from the bottom-most layer (CIM/WMI), the problem can manifest in any tool.

The Struggle for Scripters and Application Developers

People sometimes report that my tools don’t work. For example, I’ve been told that my KVP processing stack doesn’t do anything. Of course, the tool works perfectly well — as long as it has the necessary privileges. So, why didn’t I write that, and all of my other scripts, to check their privilege? Because it’s really hard, that’s why.

With a bit of searching, you’ll discover that I could just insert
#requires -RunAsAdministrator at the top of all my scripts. Problem solved, right? Well, no. Sure, it would “fix” the problem when you run the script locally. But, sometimes you’ll run the script remotely. What happens if:

  • … you run the script with an account that has administrative privileges on the target host but not on the local system?
  • … you run the script with an account that has local administrative privileges but only user privileges on the target host?

The answer to both: the desired outcome will not match your expectations.

I would need to write a solution that:

  • Checks to see if you’re running locally (harder than you might think!)
  • Checks that you’re a member of the local administrators
  • If you’re running locally, checks if your process token has administrative privileges

That’s not too tough, right? No, it’s not awful. Unfortunately, that’s not the end of it. What if you’re running locally, but invoke PowerShell Remoting with -ComputerName or Enter-PSSession or Invoke-Command? Then the entire dynamic changes yet again, because you’re not exactly remote but you’re not exactly local, either.

I’ve only attempted to fully solve this problem one time. My advanced VM settings editor includes layers of checks to try to detect all of these conditions. I spent quite a bit of time devising what I hoped would be a foolproof way to ensure that my application would warn you of insufficient privileges. I still get messages telling me that it doesn’t show any virtual machines.

I get better mileage by asking you to run my tools properly.

How to Handle the Hyper-V WMI Provider’s Security

Simply put, always ensure that you are running with the necessary privileges. If you are working locally, open PowerShell with elevated permissions:

psnowork_runas

If running remotely, always ensure that the account that you use has the necessary permissions. If your current local administrator account does not have the necessary permissions on the target system, invoke PowerShell (or whatever tool you’re using) by [Shift]+right-clicking the icon and selecting Run as different user:

psnowork_runasdifferentuser

What About the “Hyper-V Administrators” Group?

Honestly, I do not deal with this group often. I don’t understand why anyone would be a Hyper-V Administrator but not a host administrator. I believe that a Hyper-V host should not perform any other function. Trying to distinguish between the two administrative levels gives off a strong “bad plan” odor.

That said, I’ve seen more than a few reports that membership in Hyper-V Administrators does not work as expected. I have not tested it extensively, but my experiences corroborate those reports.

The Provider Might Not Be Present

All this talk about WMI mostly covers instances when you have little or no output. What happens when you have permissions, yet the system throws completely unexpected errors? Well, many things could cause that. I can’t make this article into a comprehensive troubleshooting guide, unfortunately. However, you can be certain of one thing: you cannot tell Hyper-V to carry out an action if Hyper-V is not running!

Let’s start with an obvious example. I ran Get-VM on a Windows 10 system without Hyper-V:

psnowork_getvmnohv

Nice, clear error, right? 2012 R2/Win 8.1 have a slightly different message.

Things change a bit when using the VHD cmdlets. I don’t have any current screenshots to show you because the behavior changed somewhere along the way… perhaps with Update 1 for Windows Server 2012 R2. Windows Vista/Server 2008 and later include a native driver for mounting and reading/writing VHD files. Windows 8/Server 2012 and later include a native driver for mounting and reading/writing VHDX files. However, only Hyper-V can process any of the VHD cmdlets. Get-VHD, New-VHD, Optimize-VHD, Resize-VHD, and Set-VHD require a functioning installation of Hyper-V. Just installing the Hyper-V PowerShell module won’t do it.

Currently, all of these cmdlets will show the same or a similar message to the one above. However, older versions of the cmdlets give a very cryptic message that you can’t do much with.

How to Handle a Missing Provider

This seems straightforward enough: only run cmdlets from Hyper-V module against a system with a functioning installation of Hyper-V. You can determine which functions it owns with:

When running them from a system that doesn’t have Hyper-V installed, use the ComputerName parameter.

Further Troubleshooting

With this article, I wanted to knock out two very simple reasons that Hyper-V PowerShell cmdlets (and some other tools) might not work. Of course, I realize that any given cmdlet might error for a wide variety of reasons. I am currently only addressing issues that block all Hyper-V cmdlets from running.

For troubleshooting a failure of a specific cmdlet, make sure to pay careful attention to the error message. They’re not always perfect, but they do usually point you toward a solution. Sometimes they display explicit text messages. Sometimes they include the hexadecimal error code. If they’re not clear enough to understand immediately, you can use these things in Internet searches to guide you toward an answer. You must read the error, though. Far too many times, I see “administrators” go to a forum and explain what they tried to do, but then end with, “I got an error” or “it didn’t work”. If the error message had no value the authors wouldn’t have bothered to write it. Use it.

Have any questions or feedback?

Leave a comment below!