You are browsing the archive for 2015 October.

Avatar of Florent

by Florent

Zip and Unzip with PowerShell 5

8:27 am in PowerShell by Florent

Fastest

For a specific reason of automation, I need to ZIP and UNZIP some static files automatically. I’m running Windows 10, so, PowerShell 5 is available natively:

image

In this version of PowerShell, if you type Get-Module –ListAvailable, you will be able to see the following list:

image

As you can see, a new module is available, named Microsoft.PowerShell.Archive with two commands Compress-Archive and Expand-Archive. Import this module to use it:

image

So now, to compress a single file, you can do it natively, without using an external module. I will compress a file located on my desktop, with the following command:

Compress-Archive -Path C:\Users\flore\Desktop\IP.bat -DestinationPath C:\Users\flore\Desktop\IP.zip -CompressionLevel Fastest

image

You have 3 CompressionLevel:

  • Fastest
  • NoCompression
  • Optimal

To UNZIP the file, do the following:

Expand-Archive -Path C:\Users\flore\Desktop\IP.zip -DestinationPath C:\Users\flore\Downloads\

image

You can use the switch –Force to overwrite files.

If you want to zip multiple files, you can do it with the following command:

Get-ChildItem -Path C:\Users\flore\Downloads\WS | Compress-Archive -DestinationPath C:\Users\flore\Downloads\WS.zip -CompressionLevel Optimal

image

I created my script based on these 2 commands and I scheduled a task to execute it every days. I hope that this small article will help you in your automation Sourire

Avatar of Florent

by Florent

Azure Automation: Implement the Hybrid Runbook Worker

7:23 am in Azure, Azure Automation by Florent

With Azure Automation, it is possible to execute some scripts in your local datacenter, directly from Azure. In this article, I will explain to you how to do this, by executing a script who checked the service of OMS on a specific computer and restart it if he is stopped.

The principe of the Hybrid Runbook Worker is to install an agent directly on a machine who is in your datacenter and send actions from Azure to this machine.

The first step is to create an Operations Management Suite account. Log in to https://www.microsoft.com/oms and create a new Workspace. Give a name, choose a location and give an email address:

image

If you have multiple subscription linked to your account, choose the subscription where you want to link the OMS workspace:

image

Now that OMS is available, go to Solutions Gallery and choose Automation:

image

Click on it and choose Add to add the Automation Account plugin in the OMS interface:

image

The plugin is now available:

image

Click on it to configure it. Choose the automation account that you want to link to OMS:

image

After some seconds, you will be able to see the number of runbooks and the number of jobs in the main page:

image

It’s now time to install the OMS agent on the machine in the datacenter. I choosed the SMA server to install the agent. To download the agent, click on the Settings part and choose the type of agent that you want to download. For your information, because you added the Automation plugin, the agent is different that the initial OMS agent, to just monitor your infrastructure:

SNAGHTML3fb9cdf

Launch the installation on a server:

image

image

image

Choose the Connect the agent to Microsoft Azure Operational Insights:

image

Provides the workspace ID and the key that you can found in OMS, in the settings part, where you downloaded the plugin:

SNAGHTML3fd9237

image

The installation is now done:

image

On the server where you installed the agent, you can check if the Azure Automation has been pushed, by checking if the C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation folder exists:

image

Go back to the OMS portal to see if your server is connected:

image

We will now give the possibility to our Automation Account to launch Hybrid Runbook. To do this, execute the following PowerShell scripts:

cd “C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\7.2.7037.0\HybridRegistration”
Import-Module HybridRegistration.psd1

Add-HybridRunbookWorker –Name SCUGBE -EndPoint “URL `
-Token “Primary Access Key” -Verbose

SNAGHTML4008671

Following the information that you need to fill in your PowerShell Script

SNAGHTML4015615[4]

Now, you can execute your Runbook that needs an On-Premise access, directly from Azure Automation. To show you how it works, I created a new Runbook named Get-HealthService-Status with 2 Assets. One variable, with computer named, separated by a “,” and one credential with login/password that has the administrative privilege on each server:

image

SNAGHTML40624db

Following is the code that I will execute in my Azure PowerShell Runbook:

$Servers = Get-AutomationVariable “ComputerName”
$Cred = Get-AutomationPSCredential -Name ‘LocalAdmin’

$Servers = $Servers.split(“,”);

foreach($Server in $Servers){

$service = Get-WmiObject -Class Win32_Service -ComputerName $Server -Filter “Name=’HealthService'” -Credential $Cred
if ($service.state -eq “Stopped”){

$service.StartService()
Write-Output “The service HealthService is now running on computer $Server”

} else {

Write-Output “The service HealthService is already running on computer $Server”

}
}

image

Publish it and click on Start. Choose to run it on Hybrid Worker and choose the group:

image

Click on OK to execute it. When the job is completed, go to the output to see the result:

image

We can see that for the first server, the service was already running, but on the second one, it has been started.

It is usefull to check if a critical service is running, for example every our, without having SCOM and restart it in case of failure. You can customize this script by sending an email for example if you restarted the service.

Enjoy this new feature Sourire

Avatar of Florent

by Florent

Azure Automation: Your first Runbook with PowerShell

2:55 pm in Azure, Azure Automation, PowerShell by Florent

Today, I will show you How to run your first Azure Automation Runbook.

To start this article, I have one Azure subscription, with an Active Directory linked:

SNAGHTMLc2d20

The first step will be to create a new user in this directory to execute the PowerShell runbook on Azure Automation. This account will be a standard user, but he will have the administrator rights on the subscription where the runbook will be executed:

image

image

SNAGHTMLf7287

image

Now, logout and login with this user and the temporary password to change it. When it’s done, go to https://portal.azure.com and select Automation Accounts:

image

Click on Add and complete each questions:

image

When the Automation account is created, go inside the account and select Assets. On this part, we will provide the credential to launch the runbook, a variable that we will use later in the script and a schedule for the script.

Click on Credentials > Add a credential:

image

Do the same in Variables section:

image

And with Schedules:

image

When it’s done, go back to the welcome of the Automation Accounts and select Runbooks:

image

Create a new Runbook, with the name Connect-AzureSubscription and PowerShell as Runbook type. This runbook will take your Azure credentials, provided in the Credentials section:

image

Complete with the following script, by replacing by your own values:

$Cred = Get-AutomationPSCredential -Name ‘SCUGBECred’
Add-AzureAccount -Credential $Cred

Select-AzureSubscription -SubscriptionName “Free Trial”

Click on Save and on Published:

image

Create a new Runbook, named Get-AzureVM. Paste the following script:

.\Connect-AzureSubscription.ps1
$VMNames = Get-AutomationVariable -Name ‘VMName’
$VMName = $VMNames.split(“,”);

foreach($VM in $VMName){

$serviceName = Get-AzureVM | Where {($_.Name -eq $VM)}
$service = $serviceName.ServiceName
$status = $serviceName.PowerState
Write-Output “The VM $VM with service name $service is $status”

}

You can test it with the Test pane:

SNAGHTML6edc9d

As you can see, the check is done on the 2 vm names that I wrote in my variable VMName. Click on Publish. Click on Schedule to execute the script every hour:

image

You can go on the Jobs part to see if the job has been executed correctly and see the Output. It’s possible to modify the script to send an email and so on:

image

image

This automation is very cool in case of development  environment. You can schedule to stop all VM at 9pm and restart all VM at 6AM for example.

Don’t hesitate to contact me if you want more information or help Sourire

Avatar of Florent

by Florent

Execute PowerShell through an ASP Website

3:37 pm in ASP.NET, PowerShell by Florent

I will explain to you How to execute a PowerShell script from a website with parameters. In my example, I will create a website to provide the possibility to a user to start a VM on Azure. You can adapt it depending on your needs.

The final look will be this:

image

Before starting the code creation, you MUST download the publishsettings file from Azure. On a computer where the Azure PowerShell module is installed, execute the following command:

Add-AzureAccount
Select-AzureSubscription –SubscriptionId d9703db7-XXXXXX-XXXX-X-XXXX-XXXX
Get-AzurePublishSettingsFile

SNAGHTML47712f

A web page is opened and the download of the file is starting. The file will finish by .publishsettings.

We will now create the ASP.NET code (for your information, I’m not a developer, so I do this code with my personal knowledge and maybe I have done some code mistake Sourire ). Start by creating a new project in Visual Studio. Select ASP.NET Web Application:

image

Choose the empty template:

image

Create a new folder in the Solution Explorer where the PS script will be stored. Navigate to this folder, add the publishsettings file downloaded before and create a new PowerShell script. Add the following code in it and adapt it with the path of your future IIS website:

Param(
[String]
$VMName
)
Import-Module Azure
Import-AzurePublishSettingsFile “C:\inetpub\Start-AzureVM\Sources\BizSpark-10-22-2015-credentials.publishsettings”
$azureVM = Get-AzureVM | Where-Object {$_.Name -eq $VMName}
Start-AzureVM -Name $azureVM.Name -ServiceName $azureVM.ServiceName

image

Add these 2 files in the explorer of Visual Studio:

image

Now, create a new Web Form page:

image

Use the following code to:

  • Add a Text Box
  • Add a button
  • Add a Label

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”default.aspx.cs” Inherits=”Start_AzureVM._default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Start an Azure VM</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr><td><h1>Start an Azure VM</h1></td></tr>
<tr><td><h3>Provide the name of the VM that you want to start</h3></td></tr>

<tr>
<td>
<asp:TextBox ID=”ServerName” runat=”server” TextMode=”SingleLine”></asp:TextBox>
<asp:Button ID=”ExecuteCode” runat=”server” Text=”Start VM” Width=”200″ OnClick=”ExecuteCode_Click” />
</td>
</tr>

<tr>
<td>
<asp:Label ID=”ConfirmationMessage” runat=”server”></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Open now the CS file. Paste the following code to:

  • Execute the PowerShell script with the VM Name as parameter
  • Write a confirmation message

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Start_AzureVM
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void ExecuteCode_Click(object sender, EventArgs e)
{
var SCRIPT_PATH = @”C:\inetpub\Start-AzureVM\PSScript\Start-AzureVM.ps1″;
Process _Proc = new Process();
_Proc.StartInfo.FileName = “Powershell.exe”;
_Proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_Proc.StartInfo.Arguments = @”” + SCRIPT_PATH + ” ‘” + ServerName.Text + “‘ “;
_Proc.Start();

ConfirmationMessage.Text = “The VM ” + ServerName.Text + ” is starting. Wait few minutes before trying to connect to it.”;
ServerName.Text = string.Empty;
}
}
}

Open the Web.config file. Change the langversion parameter to 5:

image

We can now publish our website. I will deploy a new VM in Azure to provide this interface through internet. It’s a simple VM where I will install:

  • IIS
  • Azure PowerShell module
  • Web Deploy 3.5
  • .Net Framework

I created 2 more endpoints for my VM. One for the Web Deploy and one for the HTTP:

image

When the creation is finished, you can deploy Azure Powershell module and Web Deploy 3.5 from the Web Platform Installer:

image

Don’t forget to install the framework that you choose when you created the project. In my case, .NET 4.5.2.

For IIS, select the Web Server feature with the ASP.NET 4.5 Role Services and the Management Service:

image

Check if the port 8172 is open in the firewall:

image

Open IIS Manager. On the IIS Server, select IIS Manager Users. Add a windows account that will have the right to connect through the web deploy:

image

Check the box to allow external communication, apply and start the website:

image

Create a new empty site (Start-AzureVM in my case). Don’t forget to change the port of the default web site if you want to use port 80. Choose an Application pool that has the rights to execute a PowerShell script:

image

image

On the new website, select IIS Manager Permissions and allow a new user:

image

Go back to visual studio. Click on Build > Publish Start-AzureVM:

image

Choose where you want to publish your site:

image

Choose the VM where you want to publish the website:

image

Provide the following information:

  • The server name with the public port of Azure
  • The new site name that we created
  • The username/password with the computer name in front
  • The URL if you want to access it when the wizard is closed (optional)

image

You need to accept the certificate when you click on Validate Connection:

image

If you have the following error:

Could not connect to the remote computer (“iis01flo.cloudapp.net”).
On the remote computer, make sure that Web Deploy is installed and that the required process (“The Web Management Service”) is started.

The remote server returned an error: (404) Not Found.

image

Go to the Control Panel and modify the Microsoft Web Deploy 3.5 software and add all features:

image

If the connection is ok, you will be able to see this:

image

Choose options that you want:

image

When you click on the preview button, you will see that VS will do. In my case it’s adding. If you modify just a file, you will see only the file, with the Action modify:

image

Click on Publish. The upload is done:

image

You can navigate to your site URL and you will be able to see this:

image

Provide the name of a VM to start it:

image

After few seconds, you can see that the VM is in starting mode in the Azure Portal:

image

You can check in the event viewer the command execution:

image

I hope this article will help you Sourire

Avatar of Florent

by Florent

RBAC with Azure

1:52 pm in Azure, Microsoft by Florent

Monday, Microsoft released an article with the possibility to perform RBAC on Azure : http://blogs.technet.com/b/ad/archive/2015/10/12/azure-rbac-is-ga.aspx

RBAC will help you to give the good rights to the good people that are using Azure.

In this article, I will explain to you, based on this article, how to implement RBAC in Azure to deploy a new Virtual Machine.

Login to the new Azure Portal ( https://portal.azure.com ) and create 2 new Resource Group. One to store Virtual Machines, Storage, etc., and the other to store the network (it’s a new configuration):

imageimage

We will now assign the right permissions to the Resource Group. On the group SCUGBE_RG_Store, assign to a group/user the role “Virtual Machine Contributor” to create virtual machines and the role “Storage Account Contributor” to give the possibility to create storage account:

image
image
image

Do the same for the Resource Group that will contain the network and give the Reader role:

image

In the Resource Group for the Network, we will create a new virtual network. Click on New > Networking > Virtual Network and select Resource Manager in the Select a deployment model section:

image

Choose a name, a range, and select the Resource Group created previously:

image

This part is optional if don’t want to allow the connection from outside.

We will create a Network Security Group to open the port 3389 for this network to allow the RDP connection. Execute the following PS script to do this:

Switch-AzureMode AzureResourceManager
$rule1 = New-AzureNetworkSecurityRuleConfig -Name rdp-rule -Description “Allow RDP” -Access Allow -Protocol Tcp -Direction Inbound -Priority 100 -SourceAddressPrefix Internet -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 3389
New-AzureNetworkSecurityGroup -ResourceGroupName SCUGBE_RG_Networks -Location “West Europe” -Name “SCUGBE-NSG” -SecurityRules $rule1

image

When it’s done, you need to assign to the user/group the “Virtual Machine Contributor” role to allow the register of the network card on it:

image

We will now add a subnet dedicated for a specific person and associate it to the previously created NSG:

image

This part is optional if don’t want to allow the connection from outside.

We will assign an IP address to the Network Resource Group to give the possibility to the user to connect remotely:

Switch-AzureMode AzureResourceManager
New-AzurePublicIpAddress -Name “SCUGBE-IPPublic” -ResourceGroupName SCUGBE_RG_Networks -Location “West Europe” -AllocationMethod Dynamic -DomainNameLabel “scugbe-rbac”

image

You need to assign to the user/group the “Virtual Machine Contributor” role to allow the register of the IP address to the VM:

imageimage

Before trying the deployment, we must assign the permission to a user to get an IP address to the right subnet. This step is only available through PowerShell:

Switch-AzureMode AzureResourceManager
Get-AzureRoleAssignment | FT DisplayName, Type, ObjectId

Get the ObjectId column:

image

Execute the script, replacing values by yours:

New-AzureRoleAssignment -ObjectId 2a83b08f-f189-4697-97e6-3fd5bcb433a3 -RoleDefinitionName “Virtual Machine Contributor” -ResourceName “SCUGBE_VNet_VMs” -ResourceType Microsoft.Network/virtualNetworks/subnets -ParentResource virtualNetworks/SCUGBE_VNet -ResourceGroupName SCUGBE_RG_Networks

image

It’s time to try the deployment of a new virtual machine, with the user assigned before. I have my 2 resource groups:

image

Deploy a new virtual machine and choose Resource Manager:

imageimageimageimage

The VM is deploying:

imageimage

image

When the VM is deployed, you can connect to it via RDP in my case:

image

And you can see objects where you have the access:

image

If I try to deploy another VM on a subnet where the access is forbiden, I will have the following error:

imageimage

image

For your information, in next release of Azure, you will be able to create your own roles.

If you have any questions, don’t hesitate to contact me Sourire