Tuesday, March 10, 2020

PowerShell 7 Chain and Ternary Operators

Introduction and Background

Welcome to this post as part of this PowerShell 7's #PSBlogWeek!   I hope you are enjoying the many posts.

As I started to think about this topic, an old Grateful Dead song kept running through my mind "Operator, Can you help m?  Help me if you please..." For a live version, listen to https://www.youtube.com/watch?v=TytIqm_d7uE.

So here is some information about a couple of the great new features in PowerShell 7, in particular, the Pipeline Chain Operators and the Ternary Operators.

In the days of Windows PowerShell, extending the PowerShell language was done by the Microsoft Windows PowerShell team.  With the move to open source, more developers can, and have, made it possible to do a lot more in PowerShell 7. PowerShell's language was modelled on C# - Jeff Snover has often said that PowerShell is on the glide scope to C#.

With PowerShell 7 comes two new operator sets: The Pipeline Chain Operators and the Ternary operators.

The Pipeline Chain operators (|| and &&) enable you to allow conditional execution of commands depending on whether the previous command succeeded for failed. You use the Ternary operators (? and :) as a short-hand way of implementing if/else type statements. These are popular among C# developers and Bash users and have long been requested within PowerShell.

These operators add new functionality to PowerShell 7. They are nice when used carefully, but can reduce the clarity of production code. Let's look at them in more detail. 

PIpeline Chain Operators

The pipeline Chain operators enable conditional execution of commands depending on whether a previous command succeeded or failed. There are two pipeline chain operators: && and ||. These operators were added to PowerShell 7 Preview 5.  Prior to PowerShell 7, you could have used If/Else to do the same thing,

These operators come originally from Posix. POSIX shells call this as AND-OR lists. The idea is that depending on whether a command is successful, you can do different things.

What is it used for?

If a pipeline is successful, this operator allows you to run some other pipeline. But if the first pipeline is unsuccessful, you can run a different pipeline. 

For example:

# Create an SSH key pair - if successful copy 
# the public key to clipboard
ssh-keygen -t rsa -b 2048 && Get-Content -Raw ~\.ssh\id_rsa.pub || clip

If the keys are generated successfully using SSH-KEYGEN (and content returned from Get-Content), then the command copies it to the clipboard. Without these operators you would have used if/else and/or try/catch - the chain operators make things a bit shorter.

Ternary Operators

The ternary operator evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false.
This sounds more complex than it is (see the example below!) These operators were added to PowerShell 7 Preview 4. 

What Is It Used For?
You typically use this operator mainly to create a string depending on the value of a boolean variable or expression. For example, you could create a string that displayed whether an AD user account was enabled based on the user's Enabled property or display whether a user is using PowerShell on a Mac. Like this:

# Is User Enabled?
# Create 2 strings
$UEMsg1         = "This user IS enabled in AD"
$UEMsg2         = "This user IS NOT enabled in AD"
# Get Details
$UserEnabled    = (Get-ADUser -Identity $UserName).Enabled
# Set Enabled/Disable String
$UserEnabledStr = $UserEnabled ? $UEMsg1 : $UEMsg2
# What does this show for an enabled user:
$UserEnabledStr
This user IS enabled in AD
#
# Anotehr example
$IsMacOS ? 'Yes' : 'No'

You Can but Should You?

I like these new operators but am not likely to use them in code I write.  Except maybe to demonstrate them.  I really do not, yet, see a great use case, except at the console. As an example of this, look at the chain operator example above. That snippet executes a command, and if successful copies a file to the clipboard. 

Personally, I'd have written it more like this:

# Create an SSH key pair - if successful, copy
# the public key to clipboard
try {
  ssh-keygen -t rsa -b 2048
}
Catch {
    # handle terminating error - left as an exercise for the reader
}
#  then    
Get-Content -Raw ~\.ssh\id_rsa.pub | clip

If I was running this from the console, I'd just run ssh-keygen. If it ran ok, then I'd type Get-Content and pipe the output to the clipboard. Typing longer lines of code is almost certain to introduce typos, especially given my lousy typing. I find doing things step by step is easiest - both to write and to understand months later when the code needs modification.

These operators have the potential to reduce the clarity of production code. Unless you know these operators, their meaning is not easy to discern. Operators like -Contains, -Eq, and -Match are both named so as to give at least some clue to their use. The '?' character an alias for Where-Object and the ':' used in PSDrive letters leading to overloaded operators.  And that can diminish the readability of production code. I am sure mileage varies - and would love to hear comments as well as seeing more great use cases.

Summary

TL;DR: Great new operators that bring requested C# Features to PowerShell - Just use them wisely.

Monday, March 09, 2020

Deploying and Managing Active Directory with PowerShell 7

I am in the process of writing a book on PowerShell 7 and one chapter is devoted to deploying and managing Active Directory. When I began looking at doing the book, it was early days for PowerShell core, and coverage was kind of poor. Early on, the AD modules did not seem to be particularly usable from within what was PowerShell Core 6.x. But having completed the chapter using PowerShell 7 RC3 and RTM, I am pleased to find that AD deployment and management works well with  PowerShell 7 (and VS Code).

Background

PowerShell 7 is based on .NET Core 3.1, whereas Windows PowerShell is based in the full .NET Framework. This means that some modules, particularly those below the System32 folder, do not work in PowerShell 7 natively.

The PowerShell team's compatibility solution for older modules is to leverage remoting. When you attempt to load a non-compatible module, Import-Module creates a remoting session into a Windows PowerShell endpoint. Then, using implicit remoting, it imports functions into the calling session. Thus you can use the commands in those modules as if they were directly supported.

The remoting session created uses the same Process transport that it uses to create background jobs. So it's relatively efficient and doesn't require WinRM. If you load multiple modules via compatibility, PowerShell just creates one session. And if you want to enter the session and look around that too is easy to do.

What DOESN'T Work?

This compatibility solution works very well but is not a universal get out of jail card. A very small number of modules will never work either directly or via the compatibility solution. Because the solution depends on remoting, some modules do not work due to object serialization that occurs when implicit remoting is invoked. The only solution is for the relevant product team to redevelop their modules (and for at least one module, Update Services, this would require a complete re-engineering of the module). At the time of writing, there are but three modules that simply do not and will not work in PowerShell 7.

The Update Services module, which you would use to manage WSUS, does not work. With this module, you use object methods to perform administrative functions (unlike almost all other modules that deliver commands or cmdlets rather than offering object Methods). The scripting model used by Update Services is reminiscent of COM programming where you instantiate an object and use its methods. A redesign to use command/cmdlets would be a great solution.

When you use the compatibility solution with this module, the methods are stripped off so you can't really do anything with the objects. The Update Service module also uses SOAP to communicate with the WSUS Server, and this is not supported in .NET Core. For that reason, without a complete redesign of the module (either to not use methods or to port the module to .NET Core and eliminate SOAP), you must manage WSUS using Windows PowerShell.

In the early Preview versions of the compatibility feature, had you tried to use some modules, you received hard to understand error messages (and of course, those object methods you need were missing.) Additionally, the error messages that were generated were not actionable and of no value.

The user experience was rather poor, even if you understood the issue. To avoid a bad user experience to this otherwise useful solution, some modules are blocked from being imported. If you try to import the UpdateServices, Import-Module raises and error. This is a much better user experience given that a few modules simply do not work in PowerShell.

The Import-Module stops you from loading modules as defined in the powershell.config.json file in PowerShell's home folder. This file also holds a list of Experimental Features which you have enabled. In my daily build folder, the file looks like this:
{ "ExperimentalFeatures": [ "PSCommandNotFoundSuggestion", "PSCultureInvariantReplaceOperator", "PSImplicitRemotingBatching", "PSNullConditionalOperators", "Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", "PSDesiredStateConfiguration.InvokeDscResource" ], "WindowsPowerShellCompatibilityModuleDenyList": [ "PSScheduledJob", "BestPractices", "UpdateServices" ], "Microsoft.PowerShell:ExecutionPolicy": "RemoteSigned" }
As you can see there are only three modules that are simply not going to work in PowerShell 7. For me, this is pretty good going and, at least for WIndows, gives IT Pros little reason not to move forward.

For those modules that DO work in the compatibility solution, there is one other minor issue you might trip over. The display XML that is used to display objects returned from a command. This display XML is not present in your PowerShell session by default which means default output may not be as nice as you might like for example when viewing the windows feature objects returned by Get-WIndowsFeature. Fortunately, there is a very simple workaround for that - just manually load the display XML.

So What About AD?

In terms of Active Directory, there are three modules that you need to use:
  • Server Manager module - this module enables you to add the AD DS feature to a server (which adds the other AD modules).
  • AD Deployment module - this module enables you to create new DCs (effectively do the job of DCPromo).
  • Active Directory module -   this module allows you to create, update, and delete objects in the AD Database such as adding users, updating groups, etc
The Server Manager module is supported by the compatibility solution and all the key commands work as they should. When you load this module, Import-Module does generate a warning message to warn you that this module is being imported via the compatibility solution. Once the module is imported, you can add, get, and remove windows features.

One small issue with this module is that the display XML that enables the output from Get-WindowsFeature to look so nice is not present by default in your PowerShell session. If this matters to you, you can deal with this by explicitly importing the display XML like this
Update-FormatData -PrependPath C:\Windows\System32\WindowsPowerShell\v1.0\modules\servermanager\feature.format.ps1xml
The AD Deployment module is also supported via the compatibility solution and was fully functional. I tested the following scenarios
  • Create a Forest Root DC
  • Create a replica DC in the first domain
  • Create DC(s) in a child Domain
  • Create an additional Forest and implement a cross-forest trust.
  • Create, update and remove OU, User, Computer, and group objects and manage group membership as well as other admin tasks (eg change password). 
The only relatively minor problem with all of this was that there are no commands to set up the cross-forest trust. To set up the trust, you just use the .NET objects and these work in .NET Core. But of course, that wasn't possible using the module in Windows PowerShell either!

The Active Directory module was one of the first modules to be ported and seems to work. I have not tested every scenario, but adding/modifying/removing users/groups/computers, managing OU contents and the like all work just as you would expect.

You can see the PowerShell 7 scripts that I developed in Github: https://github.com/doctordns/Wiley20/tree/master/08%20-%20Hyper-V. Note that these scripts are currently being developed so may change before the book is published/

Summary

PowerShell 7 both now with RC2 and when it is fully released supports deploying and managing AD forests and domains. There is a minor issue with display XML and Get-WinowsFeature which has an easy workaround. The key point is that I was able to deploy multiple forests and manage the objects inside the AD as well as with Windows PowerShell.

If you are a Windows IT Pro and use Windows PowerShell to manage Windows services and applications, you really should try PowerShell 7. It's easy to download and use and you can run it side by side with Windows PowerShell. That can enable you to enjoy the new features where you can but fall back to Windows PowerShell when you need to

What are you waiting for?







Sunday, March 08, 2020

Remoting With PowerShell 7

With version 2 of Windows PowerShell came the PowerShell Remoting feature. Remoting worked but was a bit flakey. In Version 3 it was vastly improved. Remoting came with the PowerShell Remoting Protocol (PSRP). You can read about PSRP at https://docs.microsoft.com/en-gb/openspecs/windows_protocols/ms-psrp.

In Windows PowerShell, all remoting was done using WS-Man, implemented by the WinRM service. With PowerShell 7, you can perform remoting over SSH. This article covers traditional Remtinog via WinRM and looks at what's new with PowerShell 7.

PowerShell Remoting

Here's a simplistic picture of the WS-Man based remoting stack in PowerShell:

At the bottom is HTTP / HTTPs. Remoting uses HTTP and HTTPS to carry objects between remoting clients and remoting targets. Although remoting uses HTTP, the higher levels in this stack encrypt traffic. You can use HTTPS as a transport which provides mutual authentication via certificates which can be useful in some scenarios (eg a DMZ workgroup). 

Simple Object Access Protocol (SOAP) is used to carry the data - the objects exchanged between a remoting client and target. SOAP used XML XML to hold the objects transferred between the client and target. All transferred data (objects) are first serialised into XML and deserialized at the other end. The side effect of this is that methods are stripped off. 

WS-MAN controls the end to end communications for remoting. When a remoting client establishes a connection to a remote machine, it connects to a specific endpoint. The default remoting endpoint is held in the variable $PSSessionConfigurationName. WS-MAN (implemented by the WInRM service). 

Microsoft adapted the WS-MAN service to work with Windows via the WSMV (WS-Management Protocol Extensions for Windows Vista). You can read about this layer in the Remoting stack at:https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wsmv/055dc36b-db2a-41ae-a47b-82cbfa0b4a92.

At the top of the stack is PowerShell Remoting Protocol  WIth PSRP, remoting clients establish a session with a remoting target and use that session to send structured pipelines to the target and receive the results of those pipelines. Remoting establishes a session which holds state information with what PowerShell terms a runspace. For more information on PSRP, see: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-psrp.

Remoting is a complex subject and this overview necessarily omits much of the lower-level details. 

Using Remoting

You can use remoting in three main ways:
  • Use Enter-PSSession to enter a telnet-like remote session. Commands you type are executed on the remoting target and you see the (serialized) results.
  • Use Invoke-Command to run a script block or a script file on the remoting target.
  • Use New-PSSession to create a new remoting session on the remoting target and then use the other two mechanisms to run commands on the target.
If you use Enter-PSSession, PowerShell, in effect, runs a copy of PowerShell on the target host into which you type commands and see the results. State in the remote runspace is maintained until you exit the remoting session. With using Invoke-Command,  PowerShell tears down the remote runspace when the script block or script file has completed.

If you create a remote session using New-PSSession, you can use Invoke-Command and Enter-PSSession and PowerShell maintains state. You can also specify how long PowerShell should keep the remote runspace active.

Remoting in PowerShell 7

PowerShell 7 implements the same remoting but there are three gotchas:

By default, the installation process does NOT create PowerShell 7 remoting endpoints. So after installing PowerShell 7, running Get-PSSessionConfiguration shows NO endpoints: 

You can enable the PowerShell 7 endpoints by using Enable-PSRemoting. After enabling remoting, you see two PowerShell 7 endpoints, like this.


Notice that the endpoint name no longer contains Microsoft.

In PowerShell 7, Get-PSSSionConfiguration does not show Windows PowerShell endpoints. Even though those endpoints exist, you can't see them in PowerShell 7.

If you use either Invoke-Command or Enter-PSSession, you can specify a specific endpoint. to use. If you specify no endpoint, then PowerShell remoting uses the value of $PSSessionConfigurationName. By default, this is set to http://schemas.microsoft.com/powershell/Microsoft.PowerShell. So by default, this is the behaviour on the local machine:


Once you create the PowerShell endpoints - you can use them like this:



In most cases, remoting is going to work as with Windows PowerShell. But with differences. 

I am hoping that the inability to see Windows PowerShell endpoints is a bug that can be fixed in 7.1. We'll see.



Sunday, February 23, 2020

Fun and Games With Windows Insiders Builds

For a very long time, I've quite enjoyed testing early builds of things. Getting onto the DOS 5 beta was cool, as was NT 3.1 B1. More recently, the Windows Insiders builds have been interesting. Most have been pretty simple - a bit of new functionality here, a bit there. Occasionally, stuff just doesn't work - in one build WSL was broken, in another Bluetooth was borked. Such is life - and if the feedback generated is helpful that's great.

Recently, I had some more serious issues. Build after build would simply not stick. After something like 25 failed attempts, there were two suggestions. The first was to take Hyper-V off which seemed like Voodoo (not that that is a bad thing!). The second was to do kernel debugging to help the team work out why the failures were occurring.

So I began looking at kernel debugging across the network. The directions at https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/setting-up-a-network-debugging-connection-automatically seemed to be pretty simple. And assuming you can read, they looked easy enough for me to try. 

Initially, I had issues using KDNet and got some curious error messages. KDNet said that my NIC was supported, but not plugged in. Weird as I was able to use Google to see if I could find the error message. After getting windbg setup on the debug host, KDNet on the target gave me further registry read errors. I took the opportunity of changing the network cable (although the old one worked fine in another host).  But I was stuck with networking not working. 

Using KDNet to setup kernel debugging makes changes to the boot configuration database (you can see that with BCDEdit). And that means after rebooting, the NIC appears to be gone. Looking at Device Manager, I saw a weird (to me) error message "This Device Has Been Reserved for Use by the Windows Kernel Debugger for the Duration of This Boot Session." I was about to just flatten the box, when one last bit of search engine magic pointed me to this post: https://www.majorgeeks.com/content/page/code_53_this_device_has_been_reserved_for_use_by_the_windows_kernel_debugger_for_the_duration_of_this_boot_session.html

But even so, my system was just not working and I decided that flattening it and starting over would be the fastest way to move on. But given how long it was going to take - why not try to take Hyper-V off and see if it made a difference. So after backing up 250GB of VMs, I took Hyper-V off and rebooted.

With Hyper-V removed, I was back to having just one NIC, and after configuring the IP address, it worked. Then I used WU to download the latest Insiders build - and that installed OK! Adding Hyper-V and importing the VMs went flawlessly and I'm back in business. On the latest Insider's build and with a working Hyper-V farm (and no need to reinstall all those apps...)

Thanks to some great folks: Eddie Leonard, Jason Howard, and Murray Wall were all helpful. Murray was the one who suggested removing Hyper-V (which did not seem logical). Jason/Eddie got me into a mess of my own making. It is reassuring to know that the Insiders folks are able to help!

Kernel Debugging across the network is easy if you follow directions properly. IMHO, the instructions could be improved a bit for non-dev types and to make it even clearer what to do on the host vs what to do on the target. And for sure a "how to undo what kdnet did" section would be useful! 

It is disappointing that this episode did not capture any useful output for the Insiders team.  But it's good to be back and working again.  



Friday, January 17, 2020

PowerShell 7 - Release Candidate 2 has shipped

So there I was, totally relaxed after a lovely yoga class, and at home when Twitter, well actually Steve Lee via Twitter, informed the world that RC2 had shipped. My immediate reaction was, weall as expected, to download/install it NOW!



The Install-PowerShell command from GitHub installs PowerShell for Linux, Mac, and Windows.  You can also use it to download the RTM version as well as Preview version such as Release Candidate 2. I  saved it locally and run it more or less daily to get the latest daily build. 



So what IS as Release Candidate?. In theory, an RC is a set of software that should be the final version except for some bugs. The idea of an RC is to test it and to find those bugs before the final release.; Again, in theory, an RC build should be feature complete - but sometimes 'fixes' do rather look like new features. But for the most part, RC2 is what PowerShell 7 is going to be, minus a few bugs. 

And why does this RC matter? Well - for almost all IT pros (at least Windows IT Pros), Windows PowerShell has been a core tool for a decade. For many, if not most of you, PowerShell 7 is an upgraded replacement tool. It is now fully supported in Production and is really the future of PowerShell. EVERY IT Pro that presently uses Windows PowerShell should take a close look. Speaking personally, I now use  PowerShell 7 for just about everything.

If you are an IT Pro, and if you use Windows PowerShell now. With so many neat new features, you are likely to be pleased, even if you can, today, use PowerShell 7 for everything.

Wednesday, January 15, 2020

Background Jobs in PowerShell 7

The PowerShell background jobs feature allows you to run scripts or script blocks in the background. You use the Start-Job command to start a job, and Get-Job ane Receive-Job to view jobs and to get the output of a job.

With PowerShell 7, you have the option of running a job using either PowerShell 7 (ie the default) or using Windows PowerShell 5.1. You indicate it using the -PSVersion parameter and specifying "5.1". Such jobs then run under Windows PowerShell, which can be useful if you are using PowerShell 7 but have scripts that are not yet compatible (eg using WSUS). You can kick off these scripts using background jobs, have that script run in Windows PowerShell, and then incorporate the results in a PowerShell 7 script.

Here's an example:


In this screenshot, you see I am running this in today's build of the day. I then run a simple job and view the job results. By default, PowerShell runs the script in the same version of PowerShell (ie today's daily build). Then I ran that same script but explicitly asked for Window PowerShell 5.1, what the results you can see.

This is a nice feature to assist with backwards compatibility. PowerShell 7 provides great forward compatibility but it's not yet a perfect replacement for Windows PowerShell. Features like this provide a great workaround when a command is not supported natively. 

Sunday, January 12, 2020

Planet PowerShell - A New PowerShell Resource

As I am sure you know, the Interweb contains a great deal of excellent PowerShell related content. The question is, how do you find it?

If you know what you are looking for, today's search engines are pretty awesome. I use Google and Bing a lot. In my training, I encourage 'Google Engineering' as a way to be successful with PowerShell. Search engines are outstanding, so long as you know what you are looking for.

But what if you just want to learn more?  Planet PowerShell is a community web site that aggregates blog posts from around the internet. the URL for the home page is: https://www.planetpowershell.com/. And it looks like this:


From this landing page, you can click on the Preview Button to bring up the most recent postsm like this:



From this page, you can click on the View Original Post button to view the post 

Also, if you are on Twitter, you can follow the site's Twitter feed by following  @planetpshell. That feed looks like this:



This is a great resource to help you to learn more!

Tuesday, December 24, 2019

Changing Default Parameter Values - Yet Another User for Hash Tabales

In PowerShell, the hash table is an amazingly useful .NET class - for all sorts of things: With hash tables, you can:

  • Pass a hash table and an object to Select-Object, and have the cmdlet add a calculated property to the object for later use
  • Push a hash table to Format-* and have the command create and display a new property and have it look just the way you want it.
  • Splatting, splatting, and more spatting. What a great use of hash tables.
  • Specifying property values for obscure properties in Set-ADUser/Set-ADComputer, and Set-AD-Object.
  • And many more!
But one of my favourite uses is to change the default values for certain properties within a PowerShell session or even a script.

Herre's something I am sure you have all faced. If you run a PowerShell job, you receive the output generated by using Receive-Job. By default, once you run that command, the output is removed from memory and is no longer available. Of course, you could use the -Keep parameter - if you remembered to, which I often don't.  My muscle memory is kind of not yet that well developed in this regard. So I often find my self losing output (which takes time to reproduce). I'd like to do better!

There are other commands too, that I just prefer a different value for some parameters. I'm not saying that the developers were wrong with the defaults they chose, it's just that I prefer different values. For each of these, for example -Wrap with Format-Table, I'd like to tell PowerShell to use a different default setting for a parameter on one more command. 

As ever with PowerShell - you can have it your way, and of course, there's a script for that!

The basic hashtable class is System.Collections.Hashtable. Developers across the Windows and increasingly the Linux also create specific objects derived from the hashtable class. You can read about the hash table class at: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable?view=netcore-3.1. The class is broadly the same in the full .NET and .NET core.

So how does this help to set default command values? When Windows PowerShell and PowerShell startup, the engine creates a variable: $PSDefaultParameterValues.  This variable is of type
System.Management.Automation.DefaultParameterDictionary which you can read about at: https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.defaultparameterdictionary?view=pscore-6.2.0. This object is a hash table with some improvements when used for parameter caching.

You add rows to this hash table to describe the command name, parameter name, and the new value you want PowerShell to use subsequently. For the key name, you specify the command and parameter as "<Command name>: then specify the value you want for that parameter. And of course, you can use wild cards to specify the command or property names.  You build this hash table either in a script (meaning that all commands in that script have a different default value) or stick it in the profile as I so.  So, for example, if you wanted to ensure that Receive-Job always used the -KEEP parameter, you would specify:
$PSDefaultParameterValues  @{Receive-Job:Keep = $true}
My standard profile on my laptop sets this and other values:
$PSDefaultParameterValues = @{'*:AutoSize'=$true;  '*:Wrap'=$true;'Receive-Job:Keep'=$true}
This way, any command that has an AutoSize parameter (eg Format-Table, always uses -AutoSize, likewise for any command that uses the  -Wrap parameter).

I just love hash tables - and this is another great example of where you can use one to have it your way.  


Monday, December 23, 2019

PowerShell Core/7 - Velocity

When the open-source PowerShell team shipped the first two releases of PowerShell Core 6.x, I tweeted that this was a little bit like what I remember of PowerShell V1. A product with incredible potential, a release that is a fantastic proof of concept, but with a loooooong way to go. Jeffrey Snover, in a reply tweet, agreed but made the point that PowerShell Core had a much better velocity. 

As I use PowerShell 7 RC1, I realise just how true his words were. For me, this is kind of like going from PowerShell 1 to PowerShell 5 - it's that big of an improvement in functionality, usability, and performance. 


If you navigate there you see a dashboard like this:


There are two interesting things, to me, about this dashboard. The first is that the bulk of usage is Linux with a small bit of Windows and tiny bit of Mac. But even more interesting, is the spike of usage over weekends for Linux.

As you can see from the overall graphs, usage is growing - I would expect a big increase in Windows come the new year. We'll see!

PowerShell 7 - Background Job Operator

PowerShell 7 is weeks away from release, with a Release Candidate published a few days ago. A cool new feature of PowerShell 7 is the background job operator, or &.  If you append this operator to the end of a line of code, PowerShell runs that line as a background job. Like this:


In this screenshot, I ran the Update-Help command but appended it with a "&" character. With this,  PowerShell runs the job in the background. Of course, if you exit the PowerShell session that is running this background job, the job is terminated immediately. 

This is a neat new feature. You could add the Update-Help to your PowerShell profile and every time you start PowerShell 7, the profile would ensure your help files are up to date. And unlike doing it in the foreground, updating help as a job means it's transparent -you probably would never notice the job running!


Tuesday, December 17, 2019

PowerShell 7 RC1 Has Been Released - Get It Now!

So typical of the PowerShell team - I go off to a lovely yoga class, and they ship something important. Namely the first release candidate for what is to become PowerShell 7. In a perfect world, RC1 would be the final release, except as in any sufficiently large software product there are bound to be a few minor issues that need to be ironed out. But the product is functionally complete, what you see now is that is going to ship (minus any bugs). AND - this release is fully supported in production which is important for many enterprise customers. 

You can read more here: https://devblogs.microsoft.com/powershell/announcing-the-powershell-7-0-release-candidate/. The team should be congratulated on the clear and concise manner with which they communicate, both on the blog and on social media. 

So why do RC1 and PowerShell 7 matter? Does anyone care about a release candidate of a scripting language? I see two main reasons for IT Pros and larger enterprises to begin to transition, or at the very least start the planning for that transition. 

First, it is a significant upgrade to PowerShell itself. It feels more significant than going from Windows PowerShell V2 to V3. There are a host of new features and some tremendous performance improvements, especially for very large workloads. So if you are processing all the AD computer or user accounts in a large multinational or testing connectivity to a large number of hosts using Test-Connection you are going to love PowerShell 7.

Today, many (most?) larger organisations manage production systems using suites of large and complex PowerShell scripts. For such organisations, the performance improvements alone probably justify the switch. Not mention how many little things are added that make it a joy to use.

A second reason is that Windows PowerShell is feature complete. It is not going to be improved or extended. So what works today is going to carry on being supported. All the improvements have been added to PowerShell 7. That also means leaving behind the ISE. A great tool, now in effect replaced by VS Code which is also a huge improvement.

As with any major change, there are a few things that just do not work - and won't work in PowerShell 7 when it ships early in 2020. There is a great backwards compatibility story for most of the commands that are not explicitly built using .NET Core. In the main, they work pretty well. But there are a few Windows Server modules whose command do not work and are highly unlikely to work at RTM. Two modules I'm aware of at the moment are Best Practices and the WSUS module. The WSUS module will need a major redevelopment and at this time there is no word from the team (but feel free to vote on this suggestion:  https://windowsserver.uservoice.com/forums/304618-installation-and-patching/suggestions/39267028-wsus-server-should-be-manageable-using-powershell).  

So if you are not doing so already, start using RC1. 

Thursday, December 12, 2019

Setting up the Console in PowerShell 7

I am using the latest versions of PowerShell, PowerShell 7, and loving it. Loads of new features, new operators, and better performance. I find myself using both Windows PowerShell 5.1, as well as PowerShell 7 (both preview and daily builds). This is a good environment for me as I am embarking on a book writing project on PowerShell.

Like most long-time PowerShell users, I have made use of my $Profile file to customise and optimise the environment for me. With both daily builds and preview builds and release builds - it gets hard to keep track when I'm inside a PowerShell console window. To help me out, I've added a bit of code to my profile:
If ($Host.Name -eq 'ConsoleHost') {
  $Me = whoami
  $Vn  = $PSVersionTable.PSVersion.Major
  $VNM = $PSVersionTable.PSVersion.Minor
  If ($Host.UI.RawUI.WindowTitle -match 'Administrator') {
     $WindowTitle = "ADMINISTRATOR: PowerShell $Vn.$VNM Rocks!" 
   } 
  else {
     $WindowTitle = "$Me - PowerShell $Vn.$VNM Rocks!" 
  }

If ($PSVersionTable.PSVersion.PreReleaseLabel) {
  $WindowTitle +=  "   ** $($PSVersionTable.PSVersion.PreReleaseLabel.toupper()) **" 
}

# Set it in the $Host
$Host.Ui.RawUi.WindowTitle = $WindowTitle

#  New in 5.1 - Setup PSReadline to be 'better' - For PSReadline V2.

Set-PSReadLineOption -Colors @{
  Command            = 'Cyan'
  Number             = 'White'
  Member             = 'Green'
  Operator           = 'Yellow'
  Type               = 'DarkGreen'
  Variable           = 'Yellow'
  Parameter          = 'Cyan'
  ContinuationPrompt = 'Cyan'
  String             = 'Yellow'
  Default            = 'White'}
}
This fragment, a part of my normal profile for the console hosts, sets the console host window title, based on who I am (ie is this console run as Administrator?) and it it's is a preview version build then which one (daily build vs released preview). Then uses Set-PSReadLIneOption to set the colours for my console.

These additions to my profile make it easy to see which specific version of PowerShell is running and will set the console colours to my tastes.

Wednesday, December 04, 2019

Getting the Job Done - Despite the UI

Most IT Pros are likely to want to manage various setting within Windows - both on Windows 10 and Windows Server (with the Desktop Experience!) - things like power management, a network setting, etc. Doing so means in many cases means weaving one's way through the UI to hit some window to facilitate the issue at hand. For example, if I want to set the DNS server IP address on a NIC, I have to figure out how to get, eventually to the Network Connections applet, from where I can select the NIC and make the change.

One might say. just do it with PowerShell. PowerShell is great for routine things - automation makes sense. But for one-off issues, the GUI is often just faster and easier. The issue is navigating the Windows UI. The migration of things form the Control Panel into Settings has not helped.

Almost all of the lower level applets you need to manage Windows from the UI are available to you by running a specific program. For example, to get to the Network Connections applet, just run ncpa.cpl. And if you run it from PowerShell, there is tab completion of the applet's name.

There are around 40 commands you can fun to do useful things. These commands are implemented as *.CPL and *.MSC programs. You can discover then for your self by running this:

Get-Command *.CPL, *.MSC
Here's what you should find:

Command Name What Is It?
appwiz.cpl                   Uninstall or Change A Program
azman.msc                    Authorization Manager
bthprops.cpl                 Bluetooth & Other Devices
certlm.msc                   Certificate Manager for Local Computer
certmgr.msc                  Certificate Manager for Current User
comexp.msc                   Component Services, Event Viewer, Services 
compmgmt.msc                 Computer Management, System Tools, Storage and Services
desk.cpl                     Display layout
devmgmt.msc                  Device Manager 
DevModeRunAsUserConfig.msc   Start Menu Configuration
diskmgmt.msc                 Disk Management
eventvwr.msc                 Event Viewer
Firewall.cpl                 Firewall Manager
fsmgmt.msc                   Shared Folder Management
gpedit.msc                   Local GPO Editor
hdwwiz.cpl                   Device Manager (again!)
inetcpl.cpl                  Internet Properties
intl.cpl                     Region Settings
irprops.cpl                  InfraRed - on systems with IR
joy.cpl                      Game Controller
lusrmgr.msc                  Local User Manger
main.cpl                     Mouse Properties
mmsys.cpl                    Sound Properties
ncpa.cpl                     Network Interface properties
perfmon.msc                  Performance Monitor
powercfg.cpl                 Power Configuration
printmanagement.msc          Printer Manament
rsop.msc                     Resultant Set of Policy
secpol.msc                   Local Securityh Policy
services.msc                 Services
sysdm.cpl                    System Properties
TabletPC.cpl                 Tablet and Pen Settings
taskschd.msc                 Task Scheduler
telephon.cpl                 Phone Location Information
timedate.cpl                 Time and Date
tpm.msc                      Trusted Platform Module
WF.msc                       Defender Firewall
WmiMgmt.msc                  WMI Management
wscui.cpl                    Security and Maintenance

Enjoy

Tuesday, November 26, 2019

Installing the Cascadia Code Font (using PowerShell)

In a recent article, I wrote about the new font Microsoft has created, Cascadia Code. I just love the new font and am using it with PowerShell, VS Code and more. I also use it in a variety of VMs, so automating the download and installation is important.

It turns out that downloading and installing a new font is relatively straightforward, like this:

# Install Cascadia Code
# 1. Download Cascadia Code font from GitHub
$DLPath = 'https://github.com/microsoft/cascadia-code/releases/'+
          'download/v1911.20/Cascadia.ttf'
$DLFile = 'C:\Foo\Cascadia.TTF'
Invoke-WebRequest -Uri $DLPath -OutFile $DLFile

# 2. Now Install the Font 
$Font = New-Object -Com Shell.Application
$Destination = (New-Object -ComObject Shell.Application).Namespace(0x14)
$Destination.CopyHere($DLFile,0x10)

Simples as they say.

One thing - the URL download path is hardcoded. You may need to adjust it going forward. Maybe someone can show me how to work out the latest version programmatically.

[Later]
I noticed that Blogger' editor had mangled the code - sorry but thanks for the heads up.

Friday, November 22, 2019

PowerShell 7 Preview 6 ships - Get It Now!

The PowerShell team have released another preview of PowerShell 7. This release, which I expect to be the final preview before release of PowerShell 7 early in 2020, comes with a number of fantastic new features. Over on the PowerShell blog, super-star Steve Lee notes the cool features. A total smorgasbord of wonderfulness. Read Steve's excellent post here: https://devblogs.microsoft.com/powershell/powershell-7-preview-6/.

One particular feature that caught my eye was the improvements in Test-NetConnection. As many of you know, Ping.Exe, which has been around pretty much since the dawn of IP  (as in TCP/IP). uses ICMP echo request/reply. Due to ICMP attacks, many organisations turn off ICMP - thus using Ping would show no system, even though port 80 is open and working just fine. Test-NetConnection allows you to both ping (eg using ICMP) as well as test the connection to a specific port This is a huge improvement, although the command is very slow due to it being based on WMI.

In P.6 this has been re-implemented using not WMI but .NET. And the results are pretty awesome! Here is what it looked like in PowerShell 5.1:


But take a look at the performance of PowerShell 7 P6:


That is a pretty significant improvement! And by way of comparison, using Ping.Exe would have taken over 3 seconds!

This is another example of how PowerShell 7 is set to become a worthy successor to Windows PowerShell 5.1. 

Monday, November 11, 2019

Displaying Errors in PowerShell 7 - It Gets Better

In a recent blog post, I described the new approach taken in PowerShell 7 to displaying errors. In that post, I concentrated on the new look and feel of error messages as well as the use of $ErrorView built-in variable. One thing I missed in that post was the new look for run time errors.

To demonstrate the new method of displaying run time errors, consider this script:


Ok - nothing overly exciting but that's not the point. The script should generate two errors.

In Windows PowerShell (OR if you are running PowerShell 7 with $ErrorView set to "NormalView"), running this script looks like this:


That old familiar Wall of Red Ink! Hard to see the wood for the trees. But you can see the information if you read.

Now - PowerShell 7,. if you are set $ErrorView to "ConciseView" and rerun the script you still get the terrors (or course!), but PowerShell displays them like this:


I hope you'd agree this is a great improvement in displaying runtime errors. And you can always use the new Get-Error command to get all the nitty-gritty if you need it.

As I said in that prior post, I have always loved how PowerShell displays error messaged. I have enough practice to read through that first Wall of Red Ink to see the errors quickly and easily. PowerShell 7 just makes significantly easier. 

Sunday, November 10, 2019

Viewing Errors in PowerShell 7 - Improving on Greatness

As a very long time PowerShell fan, I've always been impressed with the way PowerShell displays errors that occur in scripts or at the command line. PowerShell users are well-acquainted with the "Wall of Red Ink, as I call it:


But once you get over the visual shock and start to actually READ the error message, you begin to appreciate how good these error message actually are. They tell you what the error is and where it happened. I have long evangelised how good these messages are, once you learn to read them. B

But that is not to say things can't be improved. And indeed, in PowerShell 7, you'll find some nice improvements. NB: This blog post is being written using the latest build of the day. By the time PowerShell 7 ships, things may look the same - or different. As an aside, the daily build of PowerShell 7 in incredibly stable - hats off to the engineering team for managing that!

So in PowerShell 7, we have a new built-in variable and a new way of displaying errors. The Variable is $ErrorView which holds an object of the type: System.Management.Automation.ErrorView. This variable can hold one of three values: NormalView, CategoryView, ConciseView. With PowerShell 7, any time an error message is to be displayed, you see different views based on the value of $ErrorView.

A value of  'NormalView' results in the traditional display. But the new default setting, ConciseView, results in just the error message itself, like this:


For day to day use, ConciseView is awesome. BUT, I hear you say, where's all that detail gone. Do you HAVE to use the $Error error record collection?  NO - there's now a cmdlet for that: Get-Error.


With Get-Error you get ALL the error information inside each error record all expanded out nicely. ALL the information without having to expand error records to get to the exception details, etc.

This new feature allows you to limit the Wall of Red Ink to a Line Of Red Ink, and get the error information when you need more details.

What a great new feature!