Tag: script

Azure Automation Runbook Script

Schedule and Run PowerShell Scripts for Azure VMs using Azure Automation

A while ago I wrote a blog post on how you can run a PowerShell or Bash script against multiple Azure Virtual Machines (VMs) using Run Command. In this blog post we are going to have a look on how you can schedule and run PowerShell and Bash scripts against Azure virtual machines (VMs) using Azure Automation. For this we are going to use Azure Run Command and Azure Automation.

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 Automation delivers a cloud-based automation, operating system updates, and configuration service that supports consistent management across your Azure and non-Azure environments. It offers a couple of distinctive features, in this blog we are going to use the process automation feature, which allows you to run automation inform of PowerShell runbooks. We are going to use Azure Automation to schedule the scripts to run on Azure VMs.

Set up Azure Automation Account

First, you will need to create an Azure Automation account, this is very straight forward.

Create Azure Automation Account
Create Azure Automation Account

On the Advanced tab, you can configure the managed identity option for your new Automation account. This is the identity under which the runbook can sign in into Azure PowerShell for example. In this case I am going to use a System assigned identity.

Managed Identities
Managed Identities

Check out Microsoft Docs for more information.

Set up a system assigned managed identity, role assignment and grant permissions

After you have created the Azure Automation account, you can grant permissions to the managed identity by using Azure role-based access control (Azure RBAC). The managed identity is authenticated with Azure AD, so you don’t have to store any credentials in code.

Managed Identity and assign Azure role
Managed Identity and assign Azure role

To grant permissions for the Azure VM you want the script to run against, you can create a new Azure role assignment under identity.

Role assignment for managed identity
Role assignment for managed identity

Here you can select the scope this can be on a subscription, resource group, or even resource level. In my case I want to run this script only on Azure VMs in a specific resource group, if you want to run it on a subscription level, you can change the scope.

Create an Azure Automation PowerShell Runbook

Now you can create a new Azure Automation PowerShell runbook, which will host the script you are going to run on a schedule.

Azure Automation Runbooks
Azure Automation Runbooks

For this runbook we are going to use a PowerShell type and runtime version 7.1. With PowerShell 7 and higher we can make use of the “-parallel” parameter and some other cool features.

Now you can copy and paste the following script. You need to change the $scriptCode variable with the code you want to run against your Azure VMs.

Write-Output "Connecting to azure via Connect-AzAccount -Identity"
Connect-AzAccount -Identity 
Write-Output "Successfully connected with Automation account's Managed Identity"

# Script which should run inside the Azure VMs (Edit this)
$scriptCode = '<PASTE CODE HERE>'

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

# Run the script against all the listed VMs
Write-Output "Run Script Against Machines"
$myAzureVMs | ForEach-Object { 
	Invoke-AzVMRunCommand -ResourceGroupName $_.ResourceGroupName -Name $_.Name -CommandId 'RunPowerShellScript' -ScriptString $scriptCode
}

Should look like this:

Azure Automation Runbook Script
Azure Automation Runbook Script

Make sure after you are done editing, Save and Publish the script.

Run Azure Automation Runbook PowerShell Script against Azure VMs

Now you can start the Runbook and it will run against the Azure VMs the Managed Identity has access to. No local user account and password is required to run this.

Start PowerShell Runbook
Start PowerShell Runbook

Schedule Azure Automation Runbook

If you have tested the runbook, you can now schedule it, by linking it to a schedule. For that press Link to schedule.

Create new Schedule
Create new Schedule

You will always be able to edit the schedule or unlink it from the runbook if you don’t need it anymore.

Edit Schedules
Edit Schedules

Conclusion

I hope this post was helpful and showed you how you can use Azure Automation to schedule and run PowerShell scripts against Azure VMs using Run Command. If you have any questions or comments, feel free to leave the below.



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.



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.



Add Sleep Wait Pause in a PowerShell Script

How to Add Sleep/Wait/Pause in a PowerShell Script

Many of you know the “timeout” command we used when we created Windows Batch scripts. This pauses/waits/sleeps the script for a specific amount of time. In PowerShell, we can use the Start-Sleep cmdlet to suspend/pause/sleep/wait the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to be completed or pausing before repeating an operation.

To sleep a PowerShell script for 5 seconds, you can run the following command

Start-Sleep -Seconds 5

You can also use the -milliseconds parameter to specify how long the resource sleeps in milliseconds.

Start-Sleep -Milliseconds 25

There are also aliases for the parameter such as -s and -ms if you don’t want to type out the full name. If you want to learn more about the Start-Sleep cmdlet, check out Microsoft Docs.

Another option is to use the Read-Host cmdlet. This is waiting until the user provides any input before the script continues and with that allows you to easily pause a PowerShell script until a key press, for example:

Read-Host -Prompt "Press any key to continue..."

Usually this is used to get some input from an user, which can be reused like:

$InputFromUser = Read-Host -Prompt "Get me some input..."

To learn more about what you can do with the Read-Host cmdlet, check out Microsoft Docs.

And I think many of you know, needless to say, that if you can avoid waits in a script, that’s a good thing. 😉

I hope that quick PowerShell post gives you an overview of how to add a sleep/wait/pause in a PowerShell Script. 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.



Connect a hybrid server to Azure using Azure Arc

Connect a Hybrid Server to Azure using Azure Arc

New week, new Azure tip video!. This week we are going to have a look at how you can connect a hybrid server to Azure using Azure Arc. Azure Arc enabled servers enables you to manage and govern your Windows and Linux machines hosted across on-premises, edge, and multi-cloud environments. You’ll learn how to deploy and configure the Connected Machine agent on your Windows or Linux machine hosted outside of Azure for management by Arc enabled servers.

You can also check out the following links to learn more about Azure Arc enabled servers and how you can connect a hybrid server to Azure using Azure Arc.

Connect a Hybrid Server to Azure using Azure Arc

To connect a server running on-premises or at another cloud provider to Azure using Azure Arc, you can simply go to the Azure Portal to the Azure Arc Center and select Azure Arc enabled servers. Here you can click on the “Add” button.

Add Azure Arc Enabled Server

Add Azure Arc Enabled Server

There are currently two different ways to onboard a server. You can use an interactive script or an adding servers at scale method. With the interactive script method, you will need to provide credentials when running the script on a machine. With the onboarding at scale method, you will need to create a Service Principal Name with the minimum set of Azure permissions to onboard your servers. I highly recommend that in production environments, you o for the service principal method.

Select a method

Select a method

For demonstration purposes, we will go on with the interactive script method because this provides you with more details when you do it the first time. You will be provided with some of the prerequisites for Azure Arc enabled servers.

Add a server with Azure Arc

Add a server with Azure Arc.

You will need to provide some resources details, such as the Azure subscription, resource group, region for the metadata. You will also need to select the operating system type since the script you will get at the end will be a PowerShell script for your Windows machines and a shell script for your Linux servers.

Resource Details

Resource Details

You can now configure tags for your Azure Arc enabled server, or you can skip that step and do that later. In the end, you will be provided with a script, which you can run on the server you want to onboard to Azure Arc. This script will download the Azure Connected Machine agent, install the agent and register the server to Microsoft Azure.

Azure Arc Onboarding Script

Azure Arc Onboarding Script

This should provide you with a quick overview of how you can add a hybrid server to Azure using Azure Arc. Now the Azure Arc enabled server will show up as an Azure resource, and you can start using Azure management services for your on-premises server, like monitoring. If you want to learn more about Azure Arc, check out the recording of my session at Experts Live – Azure Hybrid Cloud Management.

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



Azure VM Run Command Run PowerShell Script

How to Run Scripts in your Azure VM using Run Command

You can access your Azure IaaS virtual machine (VM) in multiple ways like SSH or RDP, depending on your operating system and configuration. However, if you have issues with the RDP or SSH network configuration, you need to have a way to troubleshoot your virtual machine (VM). Luckily Azure offers you different management tools to work with Azure VMs for automation or troubleshooting. With the Run Command can run a PowerShell or shell script within an Azure VM remotely by using the VM agent. This scenario is especially useful when you need to troubleshoot operating system network configurations or user access configuration. For example, it can be convenient to reset RDP configurations on Windows Server virtual machines.

You use Run Command for Azure VMs through the Azure portalREST API, Azure CLI, or PowerShell. Here are some examples:

Azure VM Run Command in the Azure Portal

You can run the command directly from the Azure Portal. In the menu of the Azure VM, you can select Run command. Here you can find some predefined scripts to troubleshoot your Azure VM. In the case of a Windows VM, you will find scripts like configuring RDP port or enable PowerShell remoting. But you can also run your custom PowerShell script.

Azure VM Run Command Run PowerShell Script

Azure VM Run Command Run PowerShell Script

For Linux VMs, you will find predefined options to run a Linux shell script or ifconfig to list the network configuration.



Create Custom Script Extension for Windows - Azure Arc

How to Run Custom Scripts on Azure Arc Enabled Servers

With the latest update for Azure Arc for Servers, you are now able to deploy and use extensions with your Azure Arc enabled servers. With the Custom Script extension, you can run scripts on Azure Arc enabled servers and works similar to the custom script extension for Azure virtual machines (VMs). There is an extension for Windows and Linux servers, which is a tool that can be used to launch and execute machine customization tasks post configuration automatically.

When this Extension is added to an Azure Arc machine, it can download PowerShell and shell scripts and files from Azure storage and launch a script on the machine, which in turn can download additional software components. Custom Script Extension for Linux and Windows – Azure Arc tasks can also be automated using the Azure PowerShell cmdlets and Azure Cross-Platform Command-Line Interface (Azure CLI).

Introducing Azure Arc
For customers who want to simplify complex and distributed environments across on-premises, edge and multicloud, Azure Arc enables deployment of Azure services anywhere and extends Azure management to any infrastructure.
Learn more about Azure Arc here.

How to run Custom Scripts on Azure Arc enabled servers

To run a custom script on an Azure Arc enabled server, you can simply deploy the Custom Script Extension. You open the server you want to run the custom script in the Azure Arc server overview. Navigate to Extensions and click on Add, and select the Custom Script Extension for Windows – Azure Arc or on Linux the Custom Script Extension for Linux – Azure Arc.

Add Custom Script Extension

Add Custom Script Extension

Now you can select the PowerShell or shell script you want to run on that machine, as well as adding some optional arguments for that script.

Create Custom Script Extension for Windows - Azure Arc

Create Custom Script Extension for Windows – Azure Arc

After that, it will take a couple of minutes to run the script on the machine.

Conclusion

The Custom Script Extensions for Linux and Windows can be used to launch and execute machine customization tasks post configuration automatically.

You can learn more about how Azure Arc provides you with cloud-native management technologies for your hybrid cloud environment here, and you can find the documentation for Azure Arc enabled servers on Microsoft Docs.

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



Write PowerShell Code Online in a web browser using Visual Studio Codespaces

Write PowerShell Online using Visual Studio Codespaces

Last week the Visual Studio Services team announced a new service called Visual Studio Codespaces. Visual Studio Codespaces allows you to do cloud-hosted development for wherever you’re working. While the new services support many different programming and scripting languages, it also supports PowerShell. In this blog post, I am going to show you how you can write PowerShell code online in a web browser using Visual Studio Codespaces.

What is Visual Studio Codespaces

As mentioned, Visual Studio Codespaces (earlier known as Visual Studio Online) are cloud-hosted development environments, which are accessible from everywhere. I don’t want to go too deep into what Visual Studio Codespaces are since there are already great resources out there. However, I want to quickly give you an overview of the basics of Visual Studio Code spaces and how you can use them to write PowerShell code.

Visual Studio Codespaces gives you access to development machines, which can be cloud-hosted or self-hosted.

  • Cloud-hosted machines are machines running in the Microsoft Cloud, and you can take advantage of the power of that machine. In this case, you can use the web browser or Visual Studio Code to access that Codespace.
  • Self-hosted machines can be computers in your home, company, installed in the cloud using Azure VMs, or everywhere. Again, here you can use a remote machine using a web browser or VS Code to access that code space remotely.

Visual Studio Codespaces Overview

Visual Studio Codespaces Overview

This now allows you to have a powerful development environment that you can access and run from anywhere. I think that is pretty cool!

You can read more about the introduction of Visual Studio Codespaces here.



PowerShell ISE Mode in Visual Studio Code

How to use PowerShell ISE Mode in Visual Studio Code

If you are writing PowerShell code, you might have realized that there weren’t really improvements to the PowerShell Integrated Scripting Environment (PowerShell ISE) in the last couple of releases. With PowerShell becoming more popular on cross-platform systems, Visual Studio Code (VS Code) becomes the editor of choice. However, by default Visual Studio Code has a different behavior than the PowerShell ISE. To make it even easier, the latest PowerShell extension for Visual Studio Code, now includes PowerShell ISE Mode. PowerShell ISE Mode in Visual Studio Code, helps you to replicate and enable the settings from the following Microsoft Docs article: How to replicate the ISE experience in Visual Studio Code.

The ISE was first introduced with Windows PowerShell V2 and was re-designed with PowerShell V3. The ISE is supported in all supported versions of Windows PowerShell up to and including Windows PowerShell V5.1.

The PowerShell ISE is no longer in active feature development. As a shipping component of Windows, it continues to be officially supported for security and high-priority servicing fixes. We currently have no plans to remove the ISE from Windows.

There is no support for the ISE in PowerShell v6 and beyond.



Judge at the Nutanix Coding Challenge

Nutanix just announced the PowerShell Coding Challenge for your Nutanix environment. The challenge will be to build a script which solves a real world problem in these use cases: Provisioning/orchestration, reporting, data protection, disaster recovery and runbook automation.

Do you have what it takes to write the best script for a Nutanix environment? Find out by participating in the inaugural Total Recode challenge. This global contest gives you a platform for showcasing your best talent. May the most creative, badass coding guru win!

Want to get more familiar with the Nutanix product and test your script? Check out the Nutanix Prism APIs and our recently announced Community Edition software.

Nutanix Coding Challenge Prizes

You can win great prices:

  • Best Overall
    DJ1 Inspire 1 Drone (Valued up
    to $4000) or $4000 cash prize
  • Most Impactful
    Home Lab ($2,500 value)
    or $2,500 cash prize
  • Most Creative
    $2000 cash prize

And I am proud the be a judge in this contest with other great minds:

 

Nutanix Coding Challenge Judges

If you want to know more or join the challenge, check out the Nutantix Coding Challenge: Total Recode website.