Category: PowerShell

PowerShell Download script or file from GitHub

PowerShell: Download script or file from GitHub

Since a lot of people are starting to store their scripts and files in GitHub repositories, I often get the question, how can I download a script or a file from a Git repository using PowerShell. There are a couple of ways to you can obviously do this. You could use git and do a git clone of the repository and then run the script. In many cases however you don’t have git installed on the machine or it would be too much to clone the whole repo. So you can simply download the file or script from GitHub using PowerShell using the Invoke-WebRequest cmdlet.

Invoke-WebRequest -Uri https://raw.githubusercontent.com/thomasmaurer/demo-cloudshell/master/helloworld.ps1 -OutFile .\helloworld.ps1

This download my HelloWorld.ps1 PowerShell example file from the following example repository on GitHub.

You can also create the following one-liner which directly starts the PowerShell file using chaining in PowerShell.

Invoke-WebRequest -Uri https://raw.githubusercontent.com/thomasmaurer/demo-cloudshell/master/helloworld.ps1 -OutFile .\helloworld.ps1; .\helloworld.ps1 

You can learn more about PowerShell chain operators in my blog post here.

I hope this quick blog post on how to download scripts or files from GitHub using PowerShell was helpful. If you have any questions, feel free to leave a comment below.



Windows Package Manager WinGet CLI

Getting started with Windows Package Manager WinGet

In this blog post I want to quickly share how you can get started with the new Windows Package Manager and the WinGet CLI. At the Microsoft Build conference 2021, the team announced Windows Package Manager (WinGet) 1.0. The Windows Package Manager was first announced in 2020 as a preview for Windows Insiders. Windows Package Manager is a package manager solution that consists of a command-line tool (winget) and set of services for installing applications on Windows 10. You can use the winget command-line tool to discover, install, upgrade, remove and configure a curated set of applications.

Getting started with Windows Package Manager and WinGet

The Windows Package Manager is distributed with the App Installer from the Microsoft Store. You can also download and install the Windows Package Manager from our GitHub releases page or just directly install the latest available version. Version 1.0 of Windows Package Manager will soon ship as an automatic update via the Microsoft Store for all devices running Windows 10, version 1809 and later. It is also part of the latest Windows 11 preview builds!

To find out more about how to install the Windows Package Manager WinGet, check out my blog post. After it is installed and available on your machine, you can start using it.

Search Application to Install

To search for applications you can simply type the following command

winget search <applicationname>

For example:

winget search vscode

Search Application to install
Search Application to install

This will show applications from the winget repository. You can also enable the preview feature to use the Windows Store as a source for Winget.

You can find more information about searching applications on Microsoft Docs.

Install an application using WinGet

To install an application on Windows using the Windows Package Manager you can write the following command:

winget install <applicationname>

For example:

winget install vscode-insiders

You can also use the -h or –silent options to silent mode. This suppresses all UI and the default experience shows installer progress.

winget install vscode-insiders -h

This will install applications from the winget repository. You can also enable the preview feature to use the Windows Store as a source for Winget.

Install an application using Windows Package Manager WinGet
Install an application using Windows Package Manager WinGet

You can find more information about installing applications on Microsoft Docs.

List installed applications

You can also list all the existing applications installed on your machine using the list command.

winget list

You can also look for a spesifc application using:

winget list --name azure

In addition to the install version, the command also lists if there is an update available for the application.

List installed applications on Windows
List installed applications on Windows

You can find more information about listing applications on Microsoft Docs.

Uninstall an application using WinGet

Of course you can also uninstall applications using the uninstall command.

winget uninstall --name "Azure CLI"

It can also uninstall applications, which were not installed using the Windows Package Manager.

You can find more information about uninstalling applications on Microsoft Docs.

Update and Upgrade Applications using WinGet

One of the most important functionalities of a package manager is not just to install new applications but also keep them up-to-date. With the upgrade command you can not only see the applications where an update is available, but also where upgrade them. This also includes applications which were not installed using winget in the past.

To list all the applications with available updates you can run the following command:

winget upgrade

Update and Upgrade Applications using WinGet
Update and Upgrade Applications using WinGet

To update a specific application you can run:

winget upgrade --id Microsoft.AzureCLI

To update all applications on your machine with available updates using Windows Package Manager, you can use the following winget command:

winget upgrade --all

You can find more information about update and upgrades of applications on Microsoft Docs.

Export and Import Application list to another machine

If you have multiple machine or if you are reinstalling your computer, you can also make an export of all the applications installed on the existing machine. You can then import that file on the new or reinstalled computer, and winget will batch install all the applications.

winget export -o .\myapps.json

When the Windows Package Manager exports the JSON file, it attempts to export all the applications installed on the PC. If the winget export command is not able to match an application to an application from an available source, the export command will show a warning.

To import the list of applications on the new machine, you can run the following command:

winget import -i .\myapps.json

You can find more information about export and import of application lists on Microsoft Docs.

Additional Windows Package Manager and Winget settings

With the winget settings command you can open up the JSON setting file, where you can customize the Windows Package Manager client experience.

winget settings

A couple of settings you can change in version 1.0 and higher:

  • Auto Update Interval
  • Visual design of the progress bar
  • The install behavior including the scope, locale, and more
  • more..

To find more options and settings check out Microsoft Docs.

Repositories

You can find over 1400 unique packages in the Microsoft community repository. And if you want to add packages to the repository can check out the following docs and the Windows Package Manager Manifest Creator. This tool will help you to create a valid manifest you can the commit to the GitHub repo.

If you are looking forward to host private repositories there is also a reference implementation for the REST API source  which allows you to host your own private repository.

Conclusion

The Windows Package Manager (winget) is a fantastic tool you can use to manage and install software on your Windows 10 and Windows 11 machine. If you have any questions or you have some cool features to add to the blog, please let me know in the comments.



Getting started and Learn PowerShell on Microsoft Learn

Getting started and Learn PowerShell on Microsoft Learn!

I remember running my first commands and building my first automation using Windows PowerShell back in 2006. Since then, PowerShell became one of my daily tools to build, deploy, manage IT environments. With the release of PowerShell version 6 and now PowerShell 7, PowerShell became cross-platform. This means you can now use it on even more systems like Linux and macOS. With PowerShell becoming more and more powerful (you see what I did there ;)), more people are asking me how they can get started and learn PowerShell. Luckily we just released 5 new modules on Microsoft Learn for PowerShell.

Microsoft Learn Introduction to PowerShell

Learn about the basics of PowerShell. This cross-platform command-line shell and scripting language is built for task automation and configuration management. You’ll learn basics like what PowerShell is, what it’s used for, and how to use it.

Learning objectives

  • Understand what PowerShell is and what you can use it for.
  • Use commands to automate tasks.
  • Leverage the core cmdlets to discover commands and learn how they work.

PowerShell learn module: Introduction to PowerShell

Connect commands into a pipeline

In this module, you’ll learn how to connect commands into a pipeline. You’ll also learn about filtering leftformatting right, and other important principles.

Learning objectives

  • Explore cmdlets further and construct a sequence of them in a pipeline.
  • Apply sound principles to your commands by using filtering and formatting.

PowerShell learn module: Connect commands into a pipeline

Introduction to scripting in PowerShell

This module introduces you to scripting with PowerShell. It introduces various concepts to help you create script files and make them as robust as possible.

Learning objectives

  • Understand how to write and run scripts.
  • Use variables and parameters to make your scripts flexible.
  • Apply flow-control logic to make intelligent decisions.
  • Add robustness to your scripts by adding error management.

PowerShell learn module: Introduction to scripting in PowerShell

Write your first PowerShell code

Getting started by writing code examples to learn the basics of programming in PowerShell!

Learning objectives

  • Manage PowerShell inputs and outputs
  • Diagnose errors when you type code incorrectly
  • Identify different PowerShell elements like cmdlets, parameters, inputs, and outputs.

PowerShell learn module: Write your first PowerShell code

Automate Azure tasks using scripts with PowerShell

Install Azure PowerShell locally and use it to manage Azure resources.

Learning objectives

  • Decide if Azure PowerShell is the right tool for your Azure administration tasks
  • Install Azure PowerShell on Linux, macOS, and/or Windows
  • Connect to an Azure subscription using Azure PowerShell
  • Create Azure resources using Azure PowerShell

PowerShell learn module: Automate Azure tasks using scripts with PowerShell

Conclusion

I hope this helps you get started and learn PowerShell! If you have any questions feel free to leave a comment!



Windows 10 development virtual machine VM

Create a Windows 10 development virtual machine

If you want to create a Windows 10 development virtual machine (VM) on your Windows 10 device, Microsoft Hyper-V with the quick start gallery has you covered. So in this blog, we are going to have a look at how you can create a Windows 10 development virtual machine VM) on Windows 10. These are some easy and simple steps to automatically download and create your Windows 10 dev VM.

Microsoft offers a Windows 10 development VM which includes a preinstalled version of Windows 10 with Windows 10 SDK, Visual Studio 2019 (with the UWP, .NET desktop, and Azure workflows enabled and also includes the Windows Template Studio extension), Visual Studio Code, the Windows Subsystem for Linux, Developer mode enabled, and much more.

If you are running Windows 10 on you laptop, you can easily do all of this using Hyper-V and build-in tools. If you want to run this development virtual machine on different virtualization software options like VMware, VirtualBox, and Parallels, check out my links below.

If you want to learn more about how Hyper-V can empower developers, check out my blog post Hyper-V for Developers.

Create a Windows 10 development virtual machine using Hyper-V

To get started you will need to enable Hyper-V on your Windows 10 machine. The Hyper-V feature has a couple of prerequisites:

  • Windows 10 Enterprise, Pro, or Education
  • 64-bit Processor with Second Level Address Translation (SLAT).
  • CPU support for VM Monitor Mode Extension (VT-c on Intel CPUs).
  • Minimum of 4 GB memory.

The Hyper-V role cannot be installed on Windows 10 Home. Upgrade from Windows 10 Home edition to Windows 10 Pro by opening up Settings > Update and Security > Activation.

For more information and troubleshooting, see Windows 10 Hyper-V System Requirements.

To enabled Hyper-V on Windows 10 open up PowerShell as Administrator and run the following command:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

After that your computer will ask you to reboot.

Now you can open the Hyper-V Manager from the startmenu and on the right you can click on “Quick Create…“.

Create a Windows 10 development virtual machine
Create a Windows 10 development virtual machine

Here you can find a couple of free images you can use like Ubuntu Hyper-V Images and more. It also includes the Windows 10 dev environment VM. Select the Windows 10 dev VM and click on Create Virtual Machine. This will download the image and create the virtual machine.

Download Windows 10 dev environment VM
Download Windows 10 dev environment VM

After the VM is successfully created, you can start the VM by clicking Connect, or first edit the settings.

Virtual machine created successfully
Virtual machine created successfully

Since Windows 10 is running inside a virtual machine, by default you will be using the Windows Subsystem for Linux version 1. If you want to use the WSL 2 (Windows Subsystem for Linux 2) inside the Windows 10 dev virtual machine, you will need to enable nested virtualization on your Hyper-V machine.

Run this command as Administrator in PowerShell on the Windows 10 machine (not inside the virtual machine).

Set-VMProcessor -VMName "Windows 10 dev environment" -ExposeVirtualizationExtensions $true
Set-VMNetworkAdapter -VMName "Windows 10 dev environment" -MacAddressSpoofing On

You will need to run these commands while the virtual machine is still turned off.

Now you can start using your Windows 10 development virtual machine. With enhanced session mode on, you can also easily copy-paste files between the Windows 10 host and the VM.

Windows 10 development virtual machine VM
Windows 10 development virtual machine VM

Create a Windows 10 development virtual machine on VMware, VirtualBox, or Parallels

If you want to run your Windows 10 dev VM on VMware, VirtualBox, or Parallels, you can download images on the following website.

Conclusion

I hope this blog post was helpful. If you have any questions, feel free to leave a comment below. If you want to learn more about how Hyper-V can empower developers, check out my blog post Hyper-V for Developers.



Store Secret in PowerShell SecretStore

Stop typing PowerShell credentials in demos using PowerShell SecretManagement

We all sometimes create presentations with some PowerShell demos. And often, we need to use credentials to log in to systems for example PowerShell when delivering these presentations. This can lead that we don’t use very strong passwords because we don’t want to type them during a presentation, you see the problem? So, here is how you can use the PowerShell SecretManagement and SecretStore modules to store your demo credentials on your machine.

Doing this is pretty simple:

Install the SecretManagement and SecretStore PowerShell modules.

Install-Module Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore

Register a SecretStore to store your passwords and credentials. I this example we are using a local store to do that. Later in this blog post, we will also have a look at how you can use Azure Key Vault to store your secrets. This is handy if you are working on multiple machines.

Register-SecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault

Now we can store our credentials in the SecretStore. In this example, I am going to store the password using, and I will add some non-sensitive data as metadata to provide some additional description.

Set-Secret -name DemoAdmin01 -Secret "demoAdmin01PassWord" -Metadata @{demo = "My Hyper-V demo for Windows Server and Linux Remoting"}

You can also store other data types like PSCredential in SecretManagement. For this example, I am using just a simple string, because this works for most scenarios. 

PowerShell SecretManagement supports the following secret data types:

  • byte[]
  • string
  • SecureString
  • PSCredential
  • Hashtable
Store Secret in PowerShell SecretStore
Store Secret in PowerShell SecretStore

Now you can start using this secret in the way you need it. In my case, it is the password of one of my admin users. 

$DemoAmdin01secret = Get-Secret -Vault SecretStore -Name DemoAdmin01
$DemoAmdin01Cred = New-Object -TypeName PSCredential -ArgumentList "DemoAdmin01", $DemoAmdin01secret

As mentioned before, you can also store a PSCredential object directly in SecretManagement if that makes it easier for you.

These two lines, I could also store in my PowerShell profile I use for demos, or in my demo startup script. In this case, the credential object is available for you to use.

Use Secret Store Credentials
Use Secret Store Credentials

If you are using multiple machines and you want to keep your passwords in sync, the Azure Key Vault extension.

Install-Module Az.KeyVault
Register-SecretVault -Module Az.KeyVault -Name AzKV -VaultParameters @{ AZKVaultName = $vaultName; SubscriptionId = $subID}

Now you can store and get secrets from the Azure Key Vault and you can simply use the -Vault AzKV parameter instead of -Vault SecretStore. 

I hope this blog provides you with a short overview of how you can leverage PowerShell SecretManagement and SecretStore, to store your passwords securely. If you want to learn more about SecretManagement check out Microsoft Docs.

I also highly recommend that you read @Pierre Roman blog post on leveraging PowerShell SecretManagement to generalize a demo environment.



PowerShell Pipeline Chain Operators

How to chain multiple PowerShell commands on one line

PowerShell one-liners sometimes are an easy way to achieve something quickly. There are cases where you might want to run multiple separated PowerShell commands on one line. This can be handy if you do copy pasting of commands or if you want to make it easy for the end-user when you need to troubleshoot something. In this blog post, we will look at how you can chain and run multiple PowerShell commands on one line using pipelines and chaining commands.

PowerShell Pipelines

In many cases, you will be happy to use pipelines in PowerShell. A pipeline is a series of commands connected by pipeline operators (|). Each pipeline operator sends the results of the preceding command to the next command.

PowerShell Pipelines
PowerShell Pipelines

For example, you can do things like get a process and then stop that process.

Get-Process "notepad" | Stop-Process

This will get the notepad process and pipe it to the next command, which will then stop that process. This is a great way to get the result from one PowerShell command to the other if these commands are related.

Chaining multiple PowerShell commands in one line

But what about if these commands are not related and have nothing to do with each other? In bash for example we can use && to chain commands and put two commands together. In PowerShell, we can achieve a similar thing using firstcommand; secondcommand. Expect that in this case, it will run the second command even if the first command fails. So for example in PowerShell you can use chaining:

Get-Process "notepad"; start "https://www.thomasmaurer.ch"

In this case, we still do the first task, which is getting the notepad process, but we also want to open a website. If you can, it really makes sense to use PowerShell pipelines. However, if you want to do run multiple unrelated commands on the same line, you can use the firstcommand; secondcommand method. In this case, the second command gets executed even if the first command fails.

Chain PowerShell commands
Chain PowerShell commands

This is also handy if one of the commands, for example, is a PowerShell command and the other might just a command-line tool.

This is nothing new and is working with Windows PowerShell 5.1 (and earlier) as well as PowerShell 7.

Pipeline Chain Operators

One of the new features in PowerShell 7 are the && and || operators to chain pipelines based on conditions. These operators are known in PowerShell as pipeline chain operators. They work very simply. The && operator would execute the right-hand pipeline if the left-hand pipeline succeeded. The || operator would run the right-hand pipeline if the left-hand pipeline failed.

Get-Process "notepad" && start "https://www.thomasmaurer.ch"

If the notepad process was running, it would open the website. If notepad isn’t running, this command would just provide an error that the process “notepad” could not be found.

Get-Process "notepad" || Start-Process notepad

With this command, we would see if the notepad process is running. If it is running, the second command doesn’t get executed. If the notepad process is not running, this would now run the second command, which would start the notepad process.

PowerShell Pipeline Chain Operators
PowerShell Pipeline Chain Operators

Make sure you check out the other new PowerShell 7 features. There is some cool stuff in there, like PowerShell Predictive IntelliSense, and much more.

Conclusion

You can see there are many different ways you can chain commands in PowerShell depending on your needs. If you have any questions, feel free to leave a comment.



How to run PowerShell scripts against multiple Azure VMs in parallel by using Run Command

How to run scripts against multiple Azure VMs by using Run Command

I wrote a blog post on how to run scripts in your Azure VM by using Run Command, and explained how handy this feature is to manage Azure virtual machines (VMs). In this blog post, we are going to have a look at how you can run scripts against multiple Azure virtual machines (VMs) by using PowerShell and the Invoke-AzVMRunCommand feature.

Usually, you can access your Azure virtual machine (VM) in multiple ways, like SSH or RDP. However, if you have issues with the RDP or SSH network configuration, or don’t have any network access at all, the Run Command feature is another option. Run Command can run a PowerShell or shell script within an Azure VM remotely by using the Azure Virtual Machine Agent. This scenario is especially useful when you need to run scripts against Azure VMs where you do not have network access.

You use Run Command for Azure VMs through the Azure portalREST APIAzure CLI, or PowerShell. Like I showed you in my blog post on Microsoft Tech Community.

Azure VM Run Command in the Azure Portal
Azure VM Run Command in the Azure Portal

Using Azure PowerShell

You can also use Azure PowerShell to use the run command capabilities to run PowerShell scripts against the guest agent inside the Azure VM. For that, you can simply use the Invoke-AzVMRunCommand cmdlet from the Az PowerShell module. You can also run this command directly from Azure Cloud Shell as well.

How to run PowerShell scripts against multiple Azure VMs by using Run Command in Parallel

Now here is how you can use PowerShell 7 and the Azure PowerShell module, to run scripts against multiple Azure VMs in parallel. For that, I am using a simple Foreach-Object to run the script in “script.ps1” against all my Azure VMs in a specific resource group. By default, this would take some time because it would run through all the virtual machines in sequential order. However, with PowerShell 7 we can use the -Parallel parameter to run the commands in parallel.

#Azure Subscription I want to use
$subscriptionId = "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
#Resource Group my VMs are in
$resourceGroup = "test-azurevms-rg"

#Select the right Azure subscription
Set-AzContext -Subscription $subscriptionId

#Get all Azure VMs which are in running state and are running Windows
$myAzureVMs = Get-AzVM -ResourceGroupName $resourceGroup -status | Where-Object {$_.PowerState -eq "VM running" -and $_.StorageProfile.OSDisk.OSType -eq "Windows"}

#Run the scirpt again all VMs in parallel
$myAzureVMs | ForEach-Object -Parallel {
    $out = Invoke-AzVMRunCommand `
        -ResourceGroupName $_.ResourceGroupName `
        -Name $_.Name  `
        -CommandId 'RunPowerShellScript' `
        -ScriptPath .\script.ps1 
    #Formating the Output with the VM name
    $output = $_.Name + " " + $out.Value[0].Message
    $output   
}
How to run PowerShell scripts against multiple Azure VMs in parallel by using Run Command
How to run PowerShell scripts against multiple Azure VMs in parallel by using Run Command

I also modified the output, so it shows the VM name I have run the script against, and I selected only the Message output of Invoke-AzVMRunCommand.

You can also check out my video on YouTube:

Conclusion

I hope this blog post helps you to run PowerShell scripts against multiple Azure virtual machines (VM) in parallel using the VM run command. If you have any questions feel free to leave a comment.



Get System Uptime with PowerShell

Get System Uptime with PowerShell

Sometimes you want to know how long your system is running. There are multiple ways to get the uptime of your system using the GUI or command line. PowerShell also offers a simple way to get the system uptime. If you are running PowerShell 6 or PowerShell 7 you can get the uptime with this simple cmdlet, which works on Windows, Linux, and macOS.

To get the system uptime on Windows, Linux, or macOS using PowerShell, you can use the Get-Uptime cmdlet.

Get-Uptime

Here how that looks on Ubuntu:

Get System Uptime on Linux using PowerShell

You can also use the “-Since” parameter to return a DateTime object representing the last time that the operating system was booted.

Get-Uptime PowerShell cmdlet with -since parameter

If you are running Windows PowerShell 5 or older, you can use the CIM Instance method and the Win32_OperatingSystem class. The Win32_OperatingSystem class has a LastBootupTime property which shows the time when the computer was rebooted.

Get-CimInstance -ClassName Win32_OperatingSystem | Select LastBootUpTime

I hope that quick PowerShell post gives you an overview of how you can get the system uptime on Windows, Linux, and macOS using PowerShell. If you have any questions feel free to leave a comment. If you want to know more about how you can install and update to PowerShell 7, check out my blog post, you can also learn what is new in PowerShell 7 right here.

You can also learn about PowerShell remoting between Windows, Linux, and macOS using PowerShell remoting over SSH.



Azure PowerShell Az Predicorl ListView

Az Predictor Module – Azure PowerShell Predictions

Azure PowerShell is one of my preferred ways to build automation and manage Microsoft Azure. However, as Damien Caro (Microsoft Program Manager) mentions, the Azure PowerShell modules has over 4,000 cmdlets and, on average, ten parameters per cmdlet. This can make it hard to find the right cmdlet and parameter for what you want to do. To make this easier, the team created the Az Predictor, an intelligent command completion module for Azure PowerShell. Az Predictor will help you with predictions when you run Azure PowerShell.

In the last couple of days and weeks, I started to try out the new PowerShell Predictive IntelliSense and Az Predictor, and together with the PSReadline version, and I wouldn’t work without it anymore. it kind of reminds me of the AI-supported Azure CLI command in az find.

Az Predictor helps our Azure developers find the cmdlet they are looking for efficiently, identify the required parameters quickly, and experience fewer errors.
We worked closely with the PowerShell team to have Az be the first module that leverages this new interface and bring suggestions to the developer’s fingertips. Az Predictor takes the context of the current session into account in its suggestions. With Az Predictor’s context-aware suggestions users will be guided through the discovery of cmdlets and will not need to go to the online help as often.

Damien Caro – Microsoft Program Manager

You can read more in the official announcement blog on Microsoft Tech Community and preview 2 here.

Az Predictior Modes for Azure PowerShell

Inline mode – Suggestions of parameters and values will appear on the rest of the command line.

Azure PowerShell Az Predicorl InlineView
Azure PowerShell Az Predicorl InlineView

Listview mode – This will show several suggestions below the command line with the complete parameter set displayed.

Azure PowerShell Az Predicorl ListView
Azure PowerShell Az Predicorl ListView

Getting started with Az Predictor

Az Predictor is currently a module in preview in the PowerShell gallery. It leverages the subsystem plugin model that is available after PowerShell 7.2 and used by PSReadline 2.2.2.

You can learn more about this in my PowerShell Deep Dive reaction video.

Requirements

Install Az Predictor

To install and get started just follow these easy steps:

  1. Install PowerShell 7.2
  2. Install PSReadline 2.2
    Install-Module PSReadline -Force
  3. Install Az.Tools.Predictor preview
    Install-Module -Name Az.Tools.Predictor
  4. Enable the plugins
    Enable-AzPredictor -AllSession
  5. Enable the list view mode (Optional)
    Set-PSReadLineOption -PredictionViewStyle ListView

If you want to load Az predictor every time you start PowerShell (and trust me you want that 😉), you can add the last three commands to your PowerShell profile.

I usually use the following in my setup:

Install-Module -Name PSReadline -force
Install-Module -Name Az.Tools.Predictor
Enable-AzPredictor -AllSession
Set-PSReadLineOption -PredictionViewStyle ListView
Set-PSReadLineOption -Colors @{ InlinePrediction = "$([char]0x1b)[36;7;238m"}

Conclusion and Feedback

I hope this blog provides you with an overview of this awesome new module, which allows you to predict your Azure PowerShell commands. The team is currently looking for feedback so log issues, feature requests, or design changes on GitHub, and take a moment to fill this brief survey.

If you have any questions feel free to leave a comment.



PowerShell Predictive IntelliSense

PowerShell Predictive IntelliSense

2020 must have been a busy year because I missed one of the greatest new PowerShell features called Predictive IntelliSense. Back in November 2020, Jason Helmick announced PowerShell PSReadLine 2.1 with Predictive IntelliSense.

Update: PSReadLine version 2.2 is now general available.

One of the first things you learn when using a shell usually is tab completion. Tab provides automatic help when you are typing a command. However, we all know that the world around us gets increasingly complex. For example, the Azure PowerShell module offers over 4000 cmdlets with on average 10 parameters each. While tab-completion often is very helpful, wouldn’t it be great if the shell predicts what I am trying to do, based on my history or even with artificial intelligence (AI) pulled from the documentation? PowerShell Predictive IntelliSense is here to help with exactly that.

PowerShell Predictive IntelliSense
PowerShell Predictive IntelliSense

PowerShell Predictive IntelliSense uses my local command history and suggests the command I want to use. And with the latest version of PSReadLine 2.2.2 it can have additional plugins. These additional providers enhance predictions by providing domain-specific command and task completions, for example, for Azure PowerShell commands.

Keyboard shortcuts

Key bindings control cursor movement and additional features within the prediction. To support ListView, additional key bindings have been added to the Windows edit mode.

F2 is bound with SwitchPredictionView by default for switching between the InlineView and ListView.

Ctrl+z will revert to the original line when a list item is selected and keep the list view.

Escape will revert to the original line, whether a list item is selected, and clear the list view.

UpArrow and DownArrow are used to select an item in the ListView. To navigate history commands while the ListView is present, first press Escape to clear the ListView, then use UpArrow and DownArrow.

With Alt+A you can jump from parameter input to parameter input.

Get started with PowerShell Predictive IntelliSense

Predictive IntelliSense is implemented in the PowerShell engine and presented through the PSReadLine module. You can use the current version, which comes with PowerShell 7.2, or you can use some additional features with the latest beta release.

PSReadLine 2.2.2 + History Based Prediction

PowerShell Predictive IntelliSense InlineView
PowerShell Predictive IntelliSense InlineView

History-based predictions is available in the following versions:

Availability:

  • PSReadLine 2.2.2 currently available for download from PSGallery

Supported PowerShell versions:

Install PSReadLine 2.2.2:

Install-Module PSReadLine -Force

By default Predictive IntelliSense is disabled, you can enable it by running the following commands:

Set-PSReadLineOption -PredictionSource History

PSReadLine Plugin Prediction

PowerShell Predictive IntelliSense ListView
PowerShell Predictive IntelliSense ListView with History and Plugin

Version 2.2.2 brings ListView and a prediction plugin.

Availability:

  • PSReadLine 2.2.2 currently available for download from PSGallery

Supported PowerShell versions for ListView (History-based predictions only):

Supported PowerShell versions for the plugin subsystem (History and plugin predictions):

  • PowerShell 7.2
Install-Module PSReadLine -Force

By default, Predictive IntelliSense is disabled, you can enable it by running the following commands:

Set-PSReadLineOption -PredictionSource HistoryAndPlugin
#OPTIONAL you can also enable ListView
Set-PSReadLineOption -PredictionViewStyle ListView

One of the currently available plugins is Az Predictor, which helps you predict Azure PowerShell cmdlets. I will show you more about Az Predictor next week.

But wait there is more!

In his blog post, Jason Helmick shows even more functionality like:

  • Change the Color for Predictions using.
    Set-PSReadLineOption -Colors @{ InlinePrediction = ‘#8A0303’}
    Set-PSReadLineOption -Colors @{ InlinePrediction = ‘#2F7004’}
    Set-PSReadLineOption -Colors @{ InlinePrediction = “$([char]0x1b)[36;7;238m”}
  • Key Bindings for Predictions (List of additional suggested key bindings defined in PSReadLine SamplePSReadLineProfile.ps1)
  • and much, much more! So make sure you check out his blog post!

PowerShell Predictive IntelliSense Conclusion

I think the PowerShell Predictive IntelliSense feature is one of the best things since sliced bread. It can make you much more productive using PowerShell in so many different ways. And with the additional AI-powered modules, for example, Az Predictor, which kind of reminds me of the Azure CLI “az find” command, will help deal with more complex scenarios.

If you have any questions or comments, feel free to leave a comment below.