Shared posts

11 Feb 20:29

4 Things Every VMware Admin Should Know How to Do

by Brian Suhr

Over the years I've come across a few things I think every VMware admin should know how to do. These are tasks that are important to know when building VMware environments or troubleshooting issues. It is sometimes surprising to see the number of admins that are lacking in some of these skills.

4 Things Every VMware Admin Should Know

1. ESXTOP

This is a somewhat hidden gem to many VMware admins, especially those that come from a Windows server background. ESXTOP is a performance statistics reporting tool much like the top version included with Linux-based distributions. The VMware version is focused on presenting a ton of virtualization-specific details.

The statistics are primarily focused on details around virtual machines, disks, datastores, network, CPU, and memory, which are all important resources and items with any VMware environment. Should you be experiencing a performance issue or just want to check up on things, I think that firing up ESXTOP should be one of the first things you do.

The image below shows the simple manner in which stats are provided for you. Once you understand the data that is being presented, you can use this powerful tool to find issues in a short amount of time.

VMware ESXTOP

VMware ESXTOP

2. vCenter Alarms

This is another topic that seems pretty easy and I would assume that most VMware admins know about it. Within vCenter there are many alarms that can be set to alert you when thresholds are reached. This can be a life saver if you have no other monitoring tools or even as an early warning method before your normal toolset begins to warn people.

You could easily set up an alarm for datastore space. This is easy but a very important item, because if you run out of space you will likely have VMs crashing. The alarm can be set to warn you when the datastore reaches a certain percentage of capacity.

vCenter alarms

vCenter alarms

 

3. HA/DRS config

I cannot emphasize this item enough. Over the years I have seen many VMware clusters with improperly configured cluster settings. The importance of proper high availability and DRS settings is the difference of a smoothly running cluster and one that has trouble servicing all VMs. The other issue is that upon a hardware failure you might not be able to restart all of your virtual machines.

The ability to analyze your cluster resources against what your virtual machine requirements are is the key. You then need to select an HA protection method that will meet your requirements and understand how it will operate should one or more hosts fail. This is important because VMs may not be able to auto restart if the settings are not ideal.

4. VDS Switching

Its 2014 and I'm still seeing a lot of vSphere standard switches (VSS). Now, that not the end of the world, but when the vSphere Distributed Switch (VDS) has so much to offer, I hate to see people ignore it. If you are not purchasing Enterprise plus licensing, then the VDS is out of your reach, but I do see a lot of customers who own the licensing and who are still not taking advantage of it.

I would recommend that admins get up to speed on what the VDS has to offer and learn how to properly set it up. In the long run it can make setting up and supporting your clusters easier, and it offers many more options for advanced networking features for monitoring and troubleshooting issues.

10 Feb 14:18

Set Up a Lab with Windows PowerShell and Free Microsoft Software: Part 1

by The Scripting Guys

Summary: Use the freely available Convert-WindowsImage.ps1 to extract multiple bootable VHD files for Hyper-V Server 2012 R2.

Hey, Scripting Guy! Question Hey, Scripting Guy!

Is there an easier way to create a VHD file that already has the operating system, rather than installing it and clicking Next…Next…Next? I’d like something that could spin up a simple machine like it was a template.

—JA

Hey, Scripting Guy! Answer Hello JA,

Honorary Scripting Guy, Sean Kearney, is here. Funny you should ask. I was poking about with that idea the other day. I decided for a good simple lab, I would need the following:

  • A blank preconfigured VHD file that I could copy for a virtual machine
  • A domain controller that I could easily spin up
  • An easy way to set up the machine name and basic settings on said virtual machines
  • A simple way to edit and pass data
  • A way to keep the costs low, including software

Ideally this solution, as I was thinking to myself, could even potentially leverage Windows Powershell Desired State Configuration in the long term. More importantly, I wanted something that could be simple enough that a person with minimal knowledge of Windows PowerShell could easily use to spin up machines.

I will make some important notes. Although this solution is targeted to use the free tools, it works equally well in the full versions of Windows Server 2012 R2 and Windows 8.1. It might work with Windows Server 2012, but I haven’t tested it yet. Theoretically, it should all work.

So a few pieces came together. For software, I opted for the following free tools from Microsoft and the IT community.

Hyper-V Server 2012 R2           

Free hosting environment for virtual machines from Microsoft

Evaluation version of Windows Server 2012 R2

180-day trial of Windows Server 2012 R2 as an operating system for the virtual machines

Convert-WindowsImage.ps1

Free script written by a Microsoft partner, Pronichkin, to directly convert a WIM file to a bootable VHD. This is a great tool!

I’m going to presume that you at least know how to setup Hyper-V. If you download the free version, you’ll need to run sconfig to configure the environment. It is a really nice easy-to-use VBScript script that does all the nasty work. You’ll also have to remember that it defaults to Cmd.exe, and you will have to launch Powershell.exe to execute all of your scripts.

If you’re curious about trying to get a Hyper-V environment initially configured, here’s a series I wrote a while back on TechNet that will give you some tips: Hyper-V and the Windows PowerShell Cmdlets.

So with the presumption you have a server running Hyper-V, our first task is to get all those goodies out of the WIM file. I want to avoid typing anything as much as possible. I would also like the VHD files that I create to reflect the version of the server.

Within the latest Windows Server environments, there is a built-in cmdlet called Mount-DiskImage, which will allow us to mount either an ISO file or a VHD file directly from Windows PowerShell, and then access its contents.

$ISOFile=”C:\ISO\9600.16384.WINBLUE_RTM.130821-1623_X64FRE_SERVER_EVAL_EN-US-IRM_SSS_X64FREE_EN-US_DV5.ISO"

MOUNT-DISKIMAGE –imagepath $ISO

This is all good. But it doesn’t return the drive letter of the mounted VHD or ISO file. You can obtain this by using two other cmdlets, which we pipe together for this information:

GET-DISKIMAGE –imagepath $ISO | GET-Volume

Image of command output

If we need only the drive letter, we’ll access the property directly and store it away:

$DriveLetter=((GET-DISKIMAGE –imagepath $ISO | GET-Volume).DriveLetter)+”:”

Now with the drive letter in a scriptable state, we need to get some information about the WIM file. We need to know how many images are in the WIM file and the descriptions for each image. We will leverage this information when launching the Convert-WindowsImage.ps1 file.

To get this information, we can leverage the Get-WindowsImage cmdlet from the DISM module. We target the WIM file, and it will return a list of images, their index numbers, and descriptions for it:

GET-WINDOWSIMAGE –ImagePath ($DriveLetter+”\sources\install.wim”)

Image of command output

Now we’ll capture that information to make it useful by storing it away:

$Images=GET-WINDOWSIMAGE –ImagePath ($DriveLetter+”\sources\install.wim”)

This is where the fun begins. We’re going to make some bootable VHDs. The Convert-WindowsImage command needs to be provided only three pieces of information to make it useful:

  • Location of the WIM file
  • Index or name of the edition we want to extract
  • Name and location to assign to the VHD file

A simple example of the script in action would be this:

CONVERT-WindowsImage.PS1 –sourcepath install.wim –VHDPath c:\vhds\filename.vhd –edition ServerDataCenterCore

Or if we’re going to specify the index number (same version here too):

CONVERT-WindowsImage.PS1 –sourcepath install.wim –VHDPath c:\vhds\filename.vhd –edition 3

We already know the name and location of the WIM file. Now we start up a nice FOR loop, step through the images:

FOREACH ($Image in $Images)

{

...and grab the index number:

$Index=$Image.Index

If only I could remove the spaces from the description and make that into a file name…

Oh, right! I’m in Windows PowerShell! I can! We’ll grab the description first:

$ImageDescription=$Image.ImageDescription

…and then use the Replace method to remove the spaces:

$ImageDescription=$ImageDescription.replace(“ “,””)

Then add our destination location and file extension to our new name:

$VHDName=”C:\ISO\”+$ImageDescription+”.VHD”

And with one-fell swoop, launch the script to create a bootable VHD from a WIM file entry:

C:\ISO\Convert-WindowsImage.PS1 –sourcepath “$Driveletter\Sources\Install.wim” –Edition $Index –VHDPath $VHDName

}

Save this file into a folder. In this post, I am referencing C:\ISO, which is where I wrote this environment from. Make that location and save it there for ease-of-use. I called my CREATE-VMTemplate.PS1.

Place the Convert-WindowsImage.ps1 and CREATE-VMTemplate.PS1 in this folder and execute CREATE-VMTemplate.PS1:

.\CREATE-VMTemplate.PS1

Watch…and in about 10 minutes (depending on the speed of your computer and hard disk), you’ll have a lovely pile of VHDs that look like this:

Image of directory

Come back tomorrow when we go to the next step and make an easier way to configure the VHD before attaching it to a virtual machine.

I invite you to follow The Scripting Guys on Twitter and Facebook. If you have any questions, send an email to The Scripting Guys at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then remember eat your Cmdlets each and every day with a taste dash of Creativity.

Sean Kearney, Windows PowerShell MVP and Honorary Scripting Guy 

08 Feb 14:27

Need more DSC Resources? Announcing DSC Resource Kit Wave 2

by PowerShell Team

Good news everyone! Starting today, you can use Windows PowerShell Desired State Configuration (DSC) to configure Active Directory and SQL Server (including High Availability Groups). We are pleased to release the next wave of the DSC Resource Kit – one that enables you to start using DSC to solve your real world problems and scenarios.

When we shipped DSC in Windows Server 2012 R2, we shipped a platform with great infrastructure for configuration.  The next step for any platform like DSC is the creation of resources to make it immediately usable in significant real world scenarios.  With the resources we shipped in box, configuring SQL Server was out of reach for most of our customers.  That's changing today.  Now is the time to create a vibrant ecosystem and expansive community.

Over the past few months, we've worked hard to kick start this community.  Last month, we released the first wave of the DSC Resource Kit.  That release contained six experimental DSC resources, enabling you to configure IIS websites and Hyper-V.  Those were a limited subset of resources – a first pass at the process.  Now, we’re ready to turn it up a notch. 

This wave of the DSC Resource Kit includes fourteen new resources.  These resources are all focused on enabling you to configure Active Directory and SQL Server (including High Availability Groups).  These are real world scenarios where DSC can make an impact.  Soon, we will be blogging an involved example that uses these resources to set up a SQL High Availability Group using DSC.  In addition, we’ve updated many of the resources from the initial release, adding features and fixing bugs.

Click here to see the latest DSC Resource Kit modules.

We hope these resources will be a starting point for the DSC community – something to facilitate DSC resource creation.  Feel free to take and modify these resources to meet your needs (while following the Renaming Guidelines). We were thrilled to see that several community members created modified versions of last wave’s resources in PowerShell.Org’s GitHub repository.  Also, don’t forget that you can create your own resources – for help, check out this blog post and the DSC Resource Designer.

On a more serious note, we must reiterate that these resources come without any guarantees.  The “x” prefix stands for experimental – which means these resources are provided AS IS and are not supported through any Microsoft support program or service. We will monitor the TechNet pages, take feedback, and may provide fixes on a “fix forward” basis. 

Finally – before diving into the details – we want to invite everyone to give feedback on the DSC Resource Kit.  Are you hungry for even more resources?  Do you need DSC to enable any important scenarios?  Let us know through the comments or TechNet Q&A -- there's definitely more to come.

Description of Resources

After installing the modules, you can discover all of the resources available through the Get-DSCResource cmdlet:

 

 

Here is a brief description of each resource (for more details on a resource, check out the TechNet pages).

 

Resource

Description

Module Name

Link

xADDomain

Create and manage an Active Directory Domain

xActiveDirectory

 click here

xADDomainController

Create and manage an AD Domain Controller

xActiveDirectory

 click here

xADUser

Create and manage an AD User

xActiveDirectory

 click here

xWaitForADDomain

Pause configuration implementation until the AD Domain is available.  Used for cross machine synchronization.

xActiveDirectory

 click here

xSqlServerInstall

Create and manage a SQL Server Installation.

xSqlps

 click here

xSqlHAService

Create and manage a SQL High Availability Service.

xSqlps

 click here

xSqlHAEndpoint

Create and manage the endpoint used to access a SQL High Availability Group.

xSqlps

 click here

xSqlHAGroup

Create and manage a SQL High Availability Group.

xSqlps

 click here

xWaitForSqlHAGroup

Pause configuration implementation until a SQL HA Group is available.  Used for cross machine synchronization.

xSqlps

 click here

xCluster

Create and manage a cluster.

xFailOverCluster

 click here

xWaitForCluster

Pause configuration until a cluster is available.  Used for cross machine synchronization.

xFailOverCluster

 click here

xSmbShare

Create and manage a SMB Share.

xSmbShare

 click here

xFirewall

Create and manage Firewall rules

xNetworking

 click here

xVhdFile

Manage files to be copied into a Vhd.

xHyper-V

 click here

xWebsite

Added functionality to xWebsite to support configuration of https websites.

xWebAdministration

 click here

xVhd

Bug fixes

xHyper-V

 click here

 

Renaming Guidelines

When making changes to these resources, we urge the following practice:

1.     Update the following names by replacing MSFT with your company/community name and replacing the “x” with "c" (short for "Community") or another prefix of your choice:

a.     Module name (ex: xWebAdministration becomes cWebAdministration)

a.     Folder name (ex: MSFT_xWebsite becomes Contoso_cWebsite)

b.     Resource Name (ex: MSFT_xWebsite becomes Contoso_cWebsite)

c.     Resource Friendly Name (ex: xWebsite becomes cWebsite)

d.     MOF class name (ex: MSFT_xWebsite becomes Contoso_cWebsite)

e.     Filename for the <resource>.schema.mof (ex: MSFT_xWebsite.schema.mof becomes Contoso_cWebsite.schema.mof)

2.     Update module and metadata information in the module manifest

3.     Update any configuration that use these resources

 

We reserve resource and module names without prefixes ("x" or "c") for future use (e.g. "MSFT_WebAdministration" or "Website").  If the next version of Windows Server ships with a "Website" resource, we don't want to break any configurations that use any community modifications.  Please keep a prefix such as "c" on all community modifications.

As specified in the license, you may copy or modify this resource as long as they are used on the Windows Platform.

Requirements

The DSC Resource Kit requires Windows 8.1 or Windows Server 2012 R2 with update KB2883200 (aka the GA Update Rollup). You can check whether it is installed by running the following command:

 

PS C:\WINDOWS\system32> Get-HotFix -Id KB2883200

 

Source        Description      HotFixID      InstalledBy          InstalledOn             

------        -----------      --------      -----------          -----------             

NANA-TOUCH    Update           KB2883200     NANA-TOUCH\Admini... 9/30/2013 12:00:00 AM   

 

On supported down level operating systems, they require WMF 4.0. Refer to these previous blog posts for more information on WMF 4.0 and issues with partial installation.

Using Resources

For simple examples of configurations that use these resources, check out the respective TechNet pages. Soon, we will be blogging an involved example that details the configuration of a SQL High Availability Group using DSC. If you need help deploying the resources, see this blog post

 

Thanks,

 

John Slack

Program Manager

PowerShell Team

08 Feb 10:58

VMware Virtualization Management Blog: vSphere ESXi 5 and Remote Syslog: Make Sure You Patch/Update

By Jon Herlocker

One of the many substantial changes between VMware vSphere ESXi 4 and ESX5 was a rewrite of the syslog services, and the addition of features like support for TCP and SSL when sending logs to a remote target. However, the initial release of remote syslog support in ESX 5.0 had some significant limitations. The good news is that, as of January 2014, all of the major issues have been fixed in all versions of ESXi ESXi 5.0 to 5.5.

If you are sending your ESXi 5 hosts to a remote syslog target, then we highly recommend that you update your ESXi with the appropriate updates/patches available (listed below). Without these updates you may find yourself missing important logs when you have an issue that you need to analyze.

Once you have updated all your hosts to the versions listed below, we recommend using TCP or SSL. Without TCP, log message loss due to buffer overflows in network devices and network stacks may happen without detection.

Here are the appropriate patch/update links:

Base ESXi Version Make sure you have updated to at least Patch/Update Release Notes Date Patch/Update Was Released
5.0 vSphere ESXi 5.0 build 1489271 or higher vSphere ESXi Patch ESXi500-201401401-BG Jan 23rd, 2014
5.1 vSphere ESXi 5.1 build 1483097 or higher vSphere ESXi 5.1U2 Jan 30th, 2014
5.5 vSphere ESXi 5.5 GA build 1331820 or higher vSphere ESXi 5.5 GA Sept 22, 2013

For more information on the issues resolved with these patches, please refer to the release notes for the patch/update releases. If you have any questions, please don’t hesitate to contact VMware support or post a question in the VMware vCenter Log Insight community.

Speaking of vCenter Log Insight, if you are not yet using Log Insight, you are missing out on powerful root cause analytics and monitoring capabilities for vSphere and your entire IT ecosystem! Download a trial right away – it is so easy to setup and configure, you will have your first insights within 30 minutes.

07 Feb 14:39

Configure Windows Azure to Accept Point-to-Site VPN Connections

by Russell Smith

Microsoft introduced point-to-site VPN connections to Windows Azure in 2013, and they are currently available as a preview feature, allowing customers to connect individual on premise servers, or remote devices, to Azure via an SSTP VPN. In the first of this two-part series, I’ll show you how to configure Azure to accept a point-to-site VPN connection from Windows Server 2012 and other supported remote devices, so that you can access Azure resources.

What Is the Difference Between Site-to-Site and Point-to-Site VPNs in Windows Azure?

The key advantage of point-to-site VPNs is that Secure Socket Tunneling Protocol (SSTP) is used, so NAT firewalls can be traversed and a dedicated public-facing IPv4 address isn’t required. Site-to-site VPNs offer higher bandwidth connections to Azure, offer more flexibility, and use IPsec; so require a network edge router with a spare public-facing IPv4 address.

Site-to-site VPNs to Azure are always-on and don’t require any configuration of individual on premise clients or servers. They also allow bidirectional communication, so a server running on Azure can initiate a connection to a server running on an on-premise network.

Configure a Point-to-Site VPN in Windows Azure

Let’s start by configuring VPN support in the Azure management portal.

  • Login to the Azure management portal.
  • In the blue panel on the left, click Networks.
  • Now click +NEW in the grey bar at the bottom of the portal and click Custom Create in the pop-up dialog.
  • In the Create a Virtual Network dialog, give the new virtual network a name and select an affinity group from the drop-down menu.

If you don’t have an existing affinity group configured, select Create a new affinity group from the menu and give the new group a name and region.

  • Click the Next arrow in the bottom right of the dialog to continue.
  • On the DNS Servers and VPN Connectivity screen, I’m going to enter the IP address of a DNS server on my on premise network, and call it CONTOSOPREM.
  • Now check Configure point-to-site VPN and click the forward arrow to continue. Notice how the network diagram changes to represent the point-to-site VPN.
Configure a point-to-site VPN in Windows Azure

Configure a point-to-site VPN in Windows Azure.

  • On the Point-to-Site Connectivity screen, choose an address space from which IP addresses will be assigned to VPN clients. This address space shouldn’t overlap your on premise local network or Azure virtual network IP address ranges. For this demonstration, I have chosen 192.168.2.1/24. Click the forward arrow to continue.
Set the address space for VPN clients

Set the address space for VPN clients.

  • On the Virtual Network Address Spaces screen, define the address space and subnets for your Azure virtual network. In this demo, I’ll accept the default address space of 10.0.0.0/8 and subnet 10.0.0.0/11. The address space for the Azure virtual network must be private, and cannot overlap other virtual networks or local network sites.
  • Staying on the Virtual Network Address Spaces screen, click the green add gateway subnet button. Again, I’ll accept the default gateway subnet of 10.32.0.0/29.
  • To complete the procedure, click the tick icon on the bottom right of the dialog.
Set the address space for the Azure virtual network

Set the address space for the Azure virtual network.

  • You’ll see the new virtual network in the list. Click it.
  • On the virtual network’s screen, switch to the Dashboard tab.
  • You’ll see an error alert in the network diagram, stating that THE GATEWAY WAS NOT CREATED. To fix this, click Create Gateway at the bottom of the portal.
  • In the pop-up dialog, confirm that you want to create a gateway for the virtual network by clicking Yes.

Note that this process can take between 10 and 15 minutes to complete. Once the gateway has been created, the network diagram on the dashboard will change, and you’ll see an alert stating that a root certificate has not been uploaded.

Create the gateway for the Azure virtual network

Create the gateway for the Azure virtual network.

Create a Root Self-Signed Certificate

Before we can make a connection between our on premise server and Windows Azure, we need to create a self-signed root certificate for the VPN. While point-to-site VPNs are in preview, only self-signed certificates are supported.

  • To get the latest version of makecert, run the web installer for the Windows SDK.
  • On the Specify Location screen, accept the default install location and click Next.
  • Click Next past the Join the Customer Experience Improvement Program screen.
  • Click Accept on the License Agreement screen.
  • On the Select the features you want to install screen, uncheck everything except Windows Software Development Kit and click Install.
  • Close the installer window once the download has completed.
  • You’ll find the makecert.exe tool in the C:\Program Files (x86)\Windows Kits\8.1\bin\x64 and x86 folders.
  • Open a command prompt in the directory where you want to save your certificates. makecert.exe should be located in the same directory. To open a command prompt, right-click the directory folder while holding SHIFT, and select Open command window here from the menu.
  • In the command prompt window, type makecert -sky exchange -r -n "CN=CONTOSO2" –pe -a sha1 -len 2048 -ss My and press Enter, replacing the certificate name (CN) with something appropriate for your Azure virtual network. This command will generate a certificate in the Personal certificate store of your user account.
  • Now let’s export the certificate. Switch to the Start menu and type mmc. Click MMC in the search results.
  • In the MMC window, click File and select Add/Remove Snap-in from the menu.
  • In the Add or Remove Snap-ins window, select Certificates under Available snap-ins, click Add and then OK.
  • In the MMC window, expand Certificates – Current User, Personal, Certificates in the left pane.
  • Right-click the certificate created by makecert in the center pane and select All Tasks, Export from the menu.
  • In the Certificate Export Wizard, click Next on the welcome screen.
  • On the Export Private Key screen, select No, do not export the private key and click Next.
  • On the Export File Format screen, check DER encoded binary X.509 (.CER) and click Next.
Export the root self-signed certificate

Export the root self-signed certificate.

  • On the File to Export screen, click Browse and save the certificate to your working directory for makecert. Make sure the file has the .cer file extension. Click Next to continue.
  • Click Finish to complete the process.

In part two of this series, we’ll create another certificate for the VPN client and then download the VPN software and install it on our on premise server before testing the connection.

05 Feb 21:56

Sky release NOW TV app for Android

by Ian Dixon

Sky have released a new NOW TV streaming app for Android phones and tablets. With the app you can stream TV shows, movies and live Sky TV channels to an Android devices on a pay per view basis over Wi-Fi, 3G or 4G. The app has a beta tag and should work on Android devices running 4.0 and above.

The app is free from the Google Play Store.

This is NOWTV. Get unlimited access to the latest movies you missed at the cinema with a 30 day free trial of Sky Movies. Watch the biggest sports events, matches and games with a Sky Sports Day Pass.

Catch-up on a selection of the latest and best pay TV shows that you won’t find on Freeview with the Entertainment Month pass. No strings. No contract. Download the free app, create a NOW TV account and start watching what you want, when you want, instantly on your Android Phone or Tablet.

NOWTV Beta, is an on the move service, ensuring you don’t miss the TV you love, whenever you want. Enjoy NOWTV on your Android Device wherever you are in the UK with a Wi-Fi or 3G/4G connection.

NOW TV Beta – Key Features

* Our on demand catalogue includes hundreds of Movies and Entertainment programs to watch with the relevant pass
* Access 10 Live Entertainment channels, including Comedy CentralSky Atlantic, Sky1, Sky Living, Sky Arts 1 with an Entertainment Month Pass
* Access all Sky Sports channels, including Sky Sports F1 with a Sky Sports Day Pass
* Access all 11 Sky Movies Channels Live with a Sky Movies Month pass.

The post Sky release NOW TV app for Android appeared first on The Digital Lifestyle.com.

04 Feb 21:12

How Do I Create a Desired State Configuration?

by Damian Flynn

Over the last number of posts, we have taken a look at all the key concepts which we combine to implement our Desired State Configuration (DSC). We began with two different methods of implementing a pull server to host our DSC configurations: using a simple PowerShell Script and with a new Resource Provider for DSC published by Microsoft to implement the pull Server.

With our server online, we then changed the focus over to our nodes, where we reviewed the procedures needed to create the configurations necessary to set our nodes as pull clients to the server. We also spent a little time to consider what we may need to do, if the node had a requirement to be placed into “Maintenance Mode." But all of this work is of no value if we do not understand what we can actually manage as part of a Desired Configuration, therefore we reviewed all the “Resource Providers” that Microsoft included in the solution, ready for us to consume.

Now we need to take this next step and combine these resources to define our Desired Configuration. We also need to publish this to the pull server, so that our configured nodes can retrieve their respective configurations and apply as defined in the configuration.

Sample Configuration

Building from our initial configuration sample, we can now start to consider how to leverage PowerShell to assist in creating a more dynamic DSC configuration for our servers. Previously we illustrated some samples that combined the resource providers into a simple configuration, however, we can make this more powerful if we modify our approach just a little.

Servers and Roles

Starting with a simple hash table, we can create an list of servers to which we will apply DSC settings. Using this table, we can then define the settings that might need to be applied to ensure their configurations are appropriate for the role that they are playing in our environment.

To illustrate this approach, let’s consider this simple table as an example.

$ConfigurationData = @{
   AllNodes = @(
      @{NodeName = 'PDC-SC-DC01';    ServerType='VM';       Roles='ADService'},
      @{NodeName = 'PDC-SC-VMM01';   ServerType='VM';       Roles='WebServer'},
      @{NodeName = 'PDC-FS-SMB01';   ServerType='VM';       Roles='FileServer'}
      @{NodeName = 'PDC-VM-HOST01';  ServerType='Physical'; Roles=@('VMHost','FileServer')}
   )
}

From this, we can quickly determine, that we have four servers, that three of these are virtual, and that the roles will be deployed on the respective servers. We could get all fancy and host this data in a configuration database, but this is going to be a great starting point.

Configuration Scripts

Now, that we have a table to work from, we can get to the real fun part, and start building our configuration using a combination of PowerShell and leveraging the resource providers we introduced earlier.

To make this easier, I will share a starting configuration, and we can review some of its elements. Rather than calling out each area, I will embed comments in the configuration, so be sure to read through carefully!

# We begin defining a configuration that will be common to all our server nodes
# This will include some basics standard settings, including SNMP Services, DotNet framework
# Disabling the annoying IE Enhanced Security stuff, and finally installing my SCOM Agent
# Note that the SCOMAgent is actually a configuration of its own; this allows us to embed
# configurations within each other, making it easier to read and create complex configurations

configuration BaseServer
{
   WindowsFeature snmp
   {
      Ensure = "Present"
      Name = 'SNMP-Service'
   }

   WindowsFeature snmpwmi
   {
      Ensure = "Present"
      Name = 'SNMP-WMI-Provider'
      DependsOn= '[WindowsFeature]snmp'
   }

   WindowsFeature DotNet {
      Ensure = "Present"
      Name = "NET-Framework-45-Core"
   }

   Registry IEEnhanchedSecurity
   {
      # When "Present" then "IE Enhanced Security" will be "Disabled"
      Ensure = "Present"
      Key = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
      ValueName = "IsInstalled"
      ValueType = "DWord"
      ValueData = "0"
   }

   SCOMAgent InstallandRegister{}
}

# To leverge the power of DSC, we can define the configuration of our servers
# to be based any any combination of things, including physical and virtual.
# For virtual servers we could, for example, include integration components, while
# for physical servers we might want to deploy hardware management agents!

configuration VirtualServer
{
   BaseServer StandardBaseConfiguration {}
}

configuration PhysicalServer
{
   BaseServer StandardBaseConfiguration {}

   Dell DellManagementStuff
   {
      DependsOn  = '[BaseServer]JustTheBasics'
   }
}

# Of course to really leverage the power of DSC and PowerShell, our hash table is defined
# to describe the different roles that will be hosted on the node; therefore, we can then
# use that detail to define additional configuration instructions based on the roles

configuration UnconfiguredServer
{
   WindowsFeature PowerShellISE
   {
      Ensure = "Present"
      Name = 'PowerShell-ISE'
   }
}

configuration WebServer
{

   WindowsFeature IISServer
   {
      Ensure = "Present"
      Name = 'Web-WebServer'
   }
}

configuration FileServer
{
   WindowsFeature FileServices
   {
      Ensure = "Present"
      Name = 'FS-FileServer'
   }

   WindowsFeature FileResourceManagement
   {
      Ensure = "Present"
      Name = 'FS-Resource-Manager'
   }
}

configuration VMHost
{
   WindowsFeature Hyper-V
   {
      Ensure = "Present"
      Name = 'Hyper-V'
   }
}

# On our physical servers we choose to install the Dell Management tools
# But as these might be used on both Rack and Blade servers, we can break
# this into another configuration that can be referenced by other configurations!

configuration Dell
{
   Package DellOMSABinaries {
      Ensure    = "Present"
      Path      = "\\Server\Share\Dell\OpenManage\SysMgmtx64.msi"
      Name      = "Dell OpenManage Systems Management Software (64-Bit)"
      ProductID = "12345678-1234-12345678-12345678"
      Arguments = "ADDLOCAL=ALL"
   }
}

# Taking a similar approach, we can also manage our agents as different configurations,
# which can be easily rolled up into other configurations. In my case, this will be part
# of the base configuration for each server

Configuration SCOMAgent {

   file SCOMAgentInstaller
   {
      DestinationPath = 'c:\Installs\SCOM\Agent'
      SourcePath = "\\server\share\SCOM\Agent"
      Type = 'Directory'
      Recurse = 'False'
   }

   Package SCOMAgentPackage {
      Ensure = "Present"
      Name = "Microsoft Management Agent"
      Path = "C:\Installs\SCOM\Agent\MOMAgent.msi"
      Arguments = "USE_SETTINGS_FROM_AD=0 MANAGEMENT_GROUP=OM_Diginerve MANAGEMENT_SERVER_DNS=PDC-SC-OMMS01.diginerve.net ACTIONS_USE_COMPUTER_ACCOUNT=1 USE_MANUALLY_SPECIFIED_SETTINGS=1 SET_ACTIONS_ACCOUNT=1 AcceptEndUserLicenseAgreement=1"
      productId = "8B21425D-02F3-4B80-88CE-8F79B320D330"
      LogPath = "C:\Files\SCOMAgentInstallLog.txt"
      DependsOn = '[File]SCOMAgentInstaller'
   }
}

#
# The Heart of the Configuration! This is where all the work happens
# the Master Configuration accepts in the Configuration Data hash table to start running
# some very simple PowerShell logic to build out configurations for each server
# based on the details we hold in the hash table.
#
# Extending this configuration, you can create a profile ready for your enterprise.
# But don't forget to share it
# Create a copy at gist.github.com and put the links back in the comments!
#

configuration PetriDSC
{
   $DependsOn = $null

   if ($AllNodes.where({$_.ServerType -eq 'VM'}).NodeName)
   {
      node ($AllNodes.where({$_.ServerType -eq 'VM'})).NodeName
      {
         VirtualServer HyperV {}
         $DependsOn = '[VirtualServer]HyperV'
      }
   }

   if ($AllNodes.where({$_.ServerType -eq 'Physical'}).NodeName)
   {
      node ($AllNodes.where({$_.ServerType -eq 'Physical'})).NodeName
      {
         PhysicalServer Dell  {}
         $DependsOn = '[PhysicalServer]Dell'
      }
   }

   node ($AllNodes).NodeName
   {
      switch ($Node.Roles)
      {
         'WebServer'     { WebServer      WebServices    { DependsOn = $DependsOn } }
         'FileServer'    { FileServer     FileServices   { DependsOn = $DependsOn } }
         'VMHost'        { VMHost         VMServices     { DependsOn = $DependsOn } }
         default         { UnconfiguredServer NoRoleDefinedYet {} }
      }
   }
}

Now, we just need to register these configurations in our PowerShell environment, then we will use the master configuration, which I called PetriDCS, and pass in the hash table of our servers, which should be enough to have a set of configurations created, one per server.

Create a Desired State Configuration

The MOF files are ready. You can open them in Notepad. If everything worked to plan, each one should resemble the options you chose in your hash table.

04 Feb 21:08

Sysprep Windows Server 2012 Faster with /mode:vm Switch

by Russell Smith

How can I use sysprep to quickly create images of Windows Server 2012 for virtual machines?

Windows Server 2012’s System Preparation Tool (sysprep.exe) contains a new switch that allows system administrators to generalize the OS (remove any installation specific configuration) faster than previous versions of the tool that were designed for use on physical hardware. In this Ask the Admin, I’ll explain the new functionality and how to use it.

The sysprep tool is used to remove system-specific information from the OS so that it can be used for imaging to multiple devices. For instance, you might install Windows Server, make some specific customizations, and prepare the OS so that it can be distributed to different hardware, without having to make the customizations individually on each server.

What’s New in Sysprep for Windows Server 2012?

The new VM-mode method for generalizing a Windows 8 or Server 2012 installation only works from inside a virtual machine. Once sysprep has completed the generalization and shutdown the VM, you can copy the VM’s .vhd file and attach it to a new VM in any system that uses the same hypervisor technology.

For example, if you create the VM image in Hyper-V and then use sysprep to generalize Windows, the .vhd file should only be attached to VMs running on Hyper-V with the same hardware profile as the original VM. The same applies to .vhd images generalized on VMware and any other hypervisor. Finally, the /mode:vm switch can only be used from inside a running VM.

Use Sysprep to Generalize Windows Server 2012 Running in a VM

You will need to use sysprep from the command line, as there is no option to enable VM mode in the GUI.

  • Install Windows 8 or Windows Server 2012 (or later editions) in a virtual machine.
  • Customize the operating system as required.
  • Switch to the Start screen and type cmd. Make sure that Command Prompt is highlighted in the search results and press CTRL+SHIFT+ENTER to launch the process with administrative privileges. Give consent or enter credentials if prompted.
  • Change the working directory to System32 by typing cd c:\windows\system32\sysprep and pressing Enter.
  • To run sysprep with the standard GUI options, but also the /mode:vm switch, type sysprep.exe /oobe /generalize /shutdown /mode:vm and press Enter.

 

/mode:vm switch in Sysprep

The new /mode:vm switch in sysprep.

Once the VM has shutdown, you can create a copy of the .vhd file and attach it to new VMs in the same environment.

04 Feb 20:18

Pre order now: Mastering System Center 2012 R2 Configuration Manager!

by Peter Daalmans

Months and months of writing and hard work, even during my holidays, is almost paying Read more

The post Pre order now: Mastering System Center 2012 R2 Configuration Manager! appeared first on Configuration Manager Blog.

04 Feb 19:32

PowerTip: Learn to Use Where or ForEach in PowerShell 4.0

by The Scripting Guys

Summary: Learn the easy way to use Where or ForEach in Windows PowerShell 4.0.

Hey, Scripting Guy! Question I am running Windows PowerShell 4.0 and I want to know the easy way to use Where or ForEach.

Hey, Scripting Guy! Answer In Windows PowerShell 4.0, object arrays have a built-in .Where() and .ForEach() methods.
          You can use these methods to filter objects or perform operations with each object in the array.

For example, to use the Where() method to filter for a specific process name, run this command:

@(Get-Process).Where({ $PSItem.Name -eq 'notepad'; }).

To iterate over a list of objects in an array and perform an operation against them by using the ForEach() method, run this command:

@(Get-Process –Name notepad).ForEach({ Stop-Process -InputObject $PSItem; }).

04 Feb 14:41

Access to PowerShellCookBook.Com

by Thomas Lee

That very nice man Lee Holmes has done something really nice – in support of the current PowerShell games, he’s made access to his Cookbook web site unlimited for all. See http://www.powershellcookbook.com/ and have at it.

Thanks Lee!

29 Jan 20:49

Your Future in PowerShell

by Jeffery Hicks

I recently wrote an article that I hope will get you thinking about how PowerShell will affect your career, how it will be used and where you on the PowerShell career pipeline. Thanks in advance for taking a few minutes to read my article on the 4Sysops site and let me know what you think.

http://bit.ly/1fbS70b

29 Jan 14:00

Desired State Configuration and Local Configuration Manager

by Damian Flynn

In our previous post we covered the procedure of defining the settings we wish to use for configuring the Local Configuration Manager and leveraging the Set-DSCLocalConfigurationManager commandlet. (Editor's note: Need to catch up? Check out our previous articles on Deploying a Desired State Configuration Web Host Using Powershell and Deploying a Desired State Configuration Web Host Using DSC.)

DSC and Local Configuration Manager

In order to check if the new configuration was successfully deployed to the nodes, we can connect to the node and then leverage the command Get-DscLocalConfigurationManager, which will return its current configuring details.

Local configuration manager: Get-DscLocalConfigurationManager

However, as we are working in PowerShell there is always going to be a simpler way to do this. The second server that we configured was called PDC-SC-VMM01, so using a remote connection to the server we can also get our requested information back, as in the following example:

$session = New-CimSession -ComputerName PDC-SC-VMM01
Get-DscLocalConfigurationManager -CimSession $session

AllowModuleOverwrite           : True
CertificateID                  :
ConfigurationID                : ba59fd02-04e2-4452-a817-b8e750b4efb8
ConfigurationMode              : ApplyAndAutoCorrect
ConfigurationModeFrequencyMins : 45
Credential                     :
DownloadManagerCustomData      : {MSFT_KeyValuePair (key = "ServerUrl"), MSFT_KeyValuePair (key = "AllowUnsecureConnection")}
DownloadManagerName            : WebDownloadManager
RebootNodeIfNeeded             : True
RefreshFrequencyMins           : 15
RefreshMode                    : Pull
PSComputerName                 : PDC-SC-VMM01

Local Configuration Manager: What's Under the Hood?

When our local configuration is set to run in pull mode, the delivered meta.mof file instructs the CIM to configure the computer's task scheduler to automate the Local Configuration Manager. Essentially this might be considered as a script, which is defined to run on a schedule based our configuration.

Local configuration manager: Task Scheduler

This task launches a new PowerShell instance with the following parameters:

-NonInt -Window Hidden -Command "Invoke-CimMethod -Namespace root/Microsoft/Windows/DesiredStateConfiguration -Cl MSFT_DSCLocalConfigurationManager -Method PerformRequiredConfigurationChecks -Arguments @{Flags = [System.UInt32]1}"

Server Maintenance: Two Methods

Understanding what is happening under the hood provides us with an ability to consider what we might need to happen on the node during a maintenance procedure. If we assume that the server is configured to run in the ApplyAndAutoCorrect mode, then any maintenance we may be executing could possibly be modified if some of the change operations that we are completing conflicts with the configuration that the server is enforcing.

There are two obvious methods to put the nodes Local Configuration Manager into a stand-down configuration while the server is in maintenance mode.

1. Scheduled Tasks

We can manipulate the tasks using two simple PowerShell commands, which will place the LCM into the desired states.

Maintenance Get-ScheduledTask -TaskPath "\Microsoft\Windows\Desired State Configuration\" | Disable-ScheduledTask
Active Get-ScheduledTask -TaskPath "\Microsoft\Windows\Desired State Configuration\" | Enable-ScheduledTask

Local configuration manager: Task Scheduler

2. Local Configuration Manager

The other approach is to actually just reconfigure the LCM itself, changing the configuration mode. Of course, all we need to do is change the server from its ApplyAndAutoCorrect mode when we are in the Maintenance window and return it once the window is expired or the maintenance is completed. Unfortunately we can not just execute a simple Set-DscLocalConfigurationManager –CondigurationMode.

Instead, we need to create a configuration, which will then allow us to generate a meta.mof to apply to the Local Configuration Manager, just as we defined in previous post.

29 Jan 13:55

PowerTip: Find PowerShell Cmdlets that Accept CIM Session

by The Scripting Guys

Summary:  Learn how to find all Windows PowerShell cmdlets that accept a CIM session.

Hey, Scripting Guy! Question How can I find a list of all the Windows PowerShell cmdlets that accept a CIM session?

Hey, Scripting Guy! Answer Use the Get-Command cmdlet and specify the –CimSession parameter:

Get-Command -Parameter CimSession

Note  If you rely on dynamic loading of modules and you have not loaded a module,
this command will not report it. To ensure accurate results, load all of the modules first:

Get-Module -ListAvailable | Import-Module 

28 Jan 14:20

A One-Man Roadtrip

by nobody@smugmug.com (Trey Ratcliff)

Trey Ratcliff
A One-Man Roadtrip

A One-Man Roadtrip

28 Jan 14:11

Virtualizing Active Directory Domain Services On VMware vSphere

by nospam@example.com (Eric Sloof)

This technical white paper provides best practice guidelines for deploying AD DS on vSphere. The recommendations in this guide are not specific to a particular set of hardware or to the size and scope of a specific AD DS implementation.The examples and considerations in this document provide guidance, but do not represent strict design requirements.

 As the prominent directory service and authentication store, Active Directory Domain Services (AD DS) is in the majority of network infrastructures. In some environments AD DS is viewed as another required service, but it does not attract much attention. In other environments AD DS is treated as the business critical application (BCA) that it is.

Considering that the ability to access network resources and the Internet, look up user information, and use email often requires AD DS, it is worth understanding the importance of this service and the stability of its underlying infrastructure. In much the same way that the criticality of AD DS differs from organization to organization, so does the acceptance of virtualizing this service.

More conservative organizations choose to virtualize a portion of the AD DS environment and retain a portion on physical hardware. The cause is typically misinformation, lack of experience in virtualization, or fear of the unknown. With the release of Windows Server 2012, new features alleviate many of the legitimate concerns that administrators have about virtualizing AD DS. These new features, the latest versions of VMware® vSphere® , and recommended practices help achieve 100 percent virtualization of AD DS.

Download: Virtualizing Active Directory Domain Services On VMware vSphere 

25 Jan 16:00

Format PowerShell code for posting on PowerShell.org forums

by David Wyatt
PowerShell.org's forums have trouble displaying certain characters in script code (backticks being the most obvious annoyance.) This function can be added to your profile to convert the ISE's active window code to a PowerShell.org-friendly format on the clipboard.

Created by: David Wyatt
Published date: 1/22/2014
24 Jan 14:29

PowerShell Deep Dive First Sales

by Jeffery Hicks

PowerShell Deep Dives Last year I had the pleasure of editing PowerShell Deep Dives, published by Manning. This book is a community project with chapters contributed from MVPs and leading members of the PowerShell community. You won’t find this content anywhere else.

Anyway, I have the first royalty report from Q3 2013. Looks like we sold a little under 1500 copies. The important thing, in case you missed the original news about this project, is that all proceeds are given to charity. For this book, Save the Children received a check for $3,338.30. That’s nice but I know we can do better.

So if you’ve put off getting a copy, what are you waiting for? If you have a copy, thank you. Now spread the word and tell your colleagues to buy a copy. You can get the title in print or ebook formats. You can also buy the book from Amazon. In fact, if you’ve read the book a posted review would also help. The more reviews the attention the book can get which should lead to more sales and continued charitable contributions.

Thank you again to all of the authors and editors on this project and to those of you who have a copy on your shelf. I hope you found a few things that made it worth your investment. For the rest of you, well, you know what you need to do.

24 Jan 13:58

Windows Server 2012/R2 Documentation-in PDF

by Thomas Lee

Thanks to a post over on SpiceWorks, I’ve discovered that Microsoft has just published a full PDF of all the Windows Server 2012 and Windows Server 2012 R2 documentation. This represents the entire contents of the TechNet library on these two subjects. You can download from here: http://www.microsoft.com/en-gb/download/details.aspx?id=41182

Before you go rushing off to download – this is a big download. The pdf file itself is 110.9 MB. And definitely think hard before rushing off to print it out – it runs to 7970 pages. That’s around 8 reams of paper (or around 2 boxes). Not to mention the cost in toner!

Despite the size, this is a great document to have. I’ve loaded it onto my laptop and my Surface devices.

Technorati Tags: Windows,Documentation
22 Jan 22:22

Desired State Configuration Host Deployment: Local Configuration Manager

by Damian Flynn

Now that you have your DSC web host deployed, the next point is to figure out how we are going to actually use this new web service. In this post we will take a look at a new service that has been delivered with Windows Management Framework 4.0 / PowerShell 4.0 known as the Local Configuration Manager (LCM). It is the responsibility of this service to determine what actions should be taken based on the configuration request it receives.

If you do not have these already deployed, then please take a few moments to refer to my earlier posts to assist in getting the service online.

DSC and Local Configuration Manager (LCM)

As we described our DSC web hosts, we used the term "pull" servers to indicate that these services would be utilized by clients to pull their configuration locally from the service. The pulling action is the responsibility of the Local Configuration Manager on each machine; its default configuration is actually in push mode, which indicates that it will do nothing until a configuration is dropped in its lap.

To configure the Local Configuration Manager we create a special PowerShell DSC configuration, quite similar to the approached used as we deployed a DSC web host using DSC. The main difference this time, however, is that the configuration is targeted specifically as the LocalConfigurationManager. Using the following example, we can review the configuration options available to use as we define our settings.

configuration LocalConfigurationManager
{
  param(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$ComputerName
  )

  Node $computerName {
    LocalConfigurationManager
    {
      AllowModuleOverwrite = 'True'
      ConfigurationID = (Get-ComputerGuid $ComputerName)
      ConfigurationModeFrequencyMins = 45
      ConfigurationMode = 'ApplyAndAutoCorrect'
      RebootNodeIfNeeded = $True
      RefreshFrequencyMins = 15
      RefreshMode = 'PULL'
      DownloadManagerName = 'WebDownloadManager'
      DownloadManagerCustomData = @{
        ServerUrl = "http://PSDSCPullServer.diginerve.net/PSDSCPullServer.svc";
        AllowUnsecureConnection = "true";
      }
    }
  }
}

Let’s begin by taking a closer look at what we are defining here.

  • Line 1: Defines that we are declaring a new DSC configuration with the purpose of configuring our LocalConfigurationManager
  • Lines 3-7: Is the Standard PowerShell parameter block; in this case, we will provide the name of the computer on which the configuration is to be implemented
  • Line 8: Start of the configuration block for the named computer node
  • Line 9: Start of the actual DSC resource configuration for our LocalConfigurationManager
  • Line 10 to End: This defines the heart of the definition which implements the actual configuration setting for our LCM.

The settings we define in this section are explained a little better in the following table.

Property Sample Description
AllowModuleOverwrite TRUE In new modules are downloaded from the PULL server, do we overwrite the old versions
CertificateID GUID of the certificate.
ConfigurationID Get-ComputerGuid $ComputerName GUID to identify the computer configuration required from the PULL Server
ConfigurationMode ApplyAndAutoCorrect ApplyOnly - Configuration is applied once only.
ApplyAndMonitor - Configuration is applied only Once, and then LCM monitors for changes which are then reported to the logs
ApplyAndAutoCorrect - Configuration is applied, and then LCM monitors for changes and replies configuration if necessary
ConfigurationModeFrequencyMins 45 Duration in minutes between LCM checks.
Credential Credentials to access remote resources.
DownloadManagerCustomData ServerUrl = "http://PSDSCPullServer/PSDSCPullServer.svc";
AllowUnsecureConnection = "true";
Specifies additional data to send to the download manager.
DownloadManagerName WebDownloadManager WebDownloadManager - Specifies to use our Web Pull Server
DscFileDownloadManager - Specifices to use a SMB Share to pull from
RebootNodeIfNeeded $True Should the node reboot automatically if a configuration change requires this action
RefreshFrequencyMins 15 Duration in minutes the LCM should wait before checking the PULL server for possibly new configurations
RefreshMode PULL PUSH - The LCM is configured by push using the Start-DscConfiguration commandlet.
PULL - The LCM is configured to PULL configuations, based on the DownloadManagerName and DownloadManagerCustomData

Almost of of the configuration is quite easy to understand. Possibly the only real challenge to understand why we need to use a configuration ID, as essentially we will be configuring all our computers to contact the Pull server to get their configuration.

 

Configuration ID

If we consider this for a moment, the answer is quite logical: The ultimate objective we have with Desired State Configuration is to define a single policy to deploy to all of our servers. Then each server will implement the configuration which is appropriate to it. On the other hand, if we simply pointed our servers to the pull server and instructed the LCM to pull the configuration, it really would not know what to do, potentially configuring a big mess!

As an example, let's consider that I have a node called PDC-AD-DC01. I can quickly determine from its name that the configuration that I am likely to deploy on this node will be that of an Active Directory Domain Controller. Based on this simple extrapolation, we will define our configuration files using friendly computer names to make the details easier to read by us mortal humans. But for the purpose of configuration with DSC, we will replace these computer names with a unique GUID, ensuring that the LCM identifies itself to the pull server with its GUID (configuration ID), which will then instruct the pull server to send back the associated configuration file to the LCM specific to this node.

All we need to now worry about is maintaining a map of our friendly computer names as they match their respective GUID. We will define these to be used for the configuration IDs. Like everything in computing, there are many ways to do this, from spreadsheets to databases, but in this example, why not use the GUID of the computer as it appears in Active Directory? I am going to leverage a smart piece of PowerShell code created by Johan Åkerström which will retrieve the GUID of the computer directly from Active Directory for us: Get-ComputerGUID.

# Define Get Computer GUID Function
# Credit: Johan Åkerström
# http://blog.cosmoskey.com/powershell/desired-state-configuration-in-pull-mode-over-smb/

Function Get-ComputerGuid {
  param(
    [Parameter(Mandatory=$true)]
    [string]$ComputerName
  )

  process {
    ([guid]([adsisearcher]"(samaccountname=$ComputerName`$)").FindOne().Properties["objectguid"][0]).Guid
  }
}

Wrapping Up

To pull this together, I finally launch a PowerShell 4.0 session and define both my function and my configuration, which will ensure that they are ready to be executed.

Desired State Configuration: Local Configuration Management

Next, I can execute my new configuration, passing in the parameter that defines the name of my computer, in addition to the path to where I would like the output to be stored. In this example, the computer is PDC-SC-VMM01, and the output folder c:\workspace. The result of this command will be created in the output folder delivering a new meta.mof file. This meta.mof file is all that is required to configure our server. Using Notepad we can see how this looks.

Desired State Configuration: Local Configuration Management

In the center of the file, we will see the instance of MSFT_DSCMetaConfiguration configuration, which contains all the options we defined in our configuration file. However, we can now also see that the ConfigurationID has now been replaced with the computers GUID as retrieved from Active Directory.

All that remains now is to apply this new setting to our server, which again is quite simply implemented with the following command.

Set-DscLocalConfigurationManager -Path c:\workspace –Verbose

I have enabled the –verbose option so we can observe this magic. To add a little excitement, I have multiple servers which I am going to configure the LCM for our pull server, so I also created a profile for PDC-RD-APPS01 and store it in the same folder C:\Workspace.

Desired State Configuration: Local Configuration Management

If you look at the screen capture, you can see that after running the command to start the LCM configuration, the two meta.mof files in my working folder were read. Then the command made a remote CIM connection to both servers and pushed the new configuration directly to them.

NICE!

22 Jan 21:52

Using PowerShell CIM Cmdlets to Explore WMI Classes

by The Scripting Guys

Summary: Microsoft Scripting Guy, Ed Wilson, shares an excerpt about WMI and CIM from his book, Windows PowerShell Best Practices.

Microsoft Scripting Guy, Ed Wilson, is here. Today I have an excerpt from my new book, Windows PowerShell Best Practices, which is published by Microsoft Press.

Image of book

The CIM cmdlets in Windows PowerShell support multiple ways of exploring WMI. They work well when you are working in an interactive fashion. For example, Tab expansion expands the namespace when you use the CIM cmdlets; thereby permitting exploring namespaces that might not otherwise be very discoverable. You can even use this technique to drill down into namespaces. All CIM classes support Tab expansion of the Namespace parameter, but to explore WMI classes, you want to use the Get-CimClass cmdlet.

Note  The default WMI namespace on all Windows operating systems after Windows NT 4.0 is Root/Cimv2. Therefore, all of the CIM cmdlets default to Root/Cimv2. The only time you need to change the default WMI namespace (via the Namespace parameter) is when you need to use a WMI class from a non-default WMI namespace.

Using the Classname parameter

When you use the Get-CimClass cmdlet, you can use wildcard characters for the Classname parameter to enable you to quickly identify potential WMI classes for perusal. You can also use wildcard characters for the Qualifiername parameter. In the following example, the Get-CimClass cmdlet looks for WMI classes related to computers:

PS C:\> Get-CimClass -ClassName *computer*

   NameSpace: ROOT/CIMV2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_ComputerSystemEvent           {}                   {SECURITY_DESCRIPTOR, TIME_CR...
Win32_ComputerShutdownEvent         {}                   {SECURITY_DESCRIPTOR, TIME_CR...
CIM_ComputerSystem                  {}                   {Caption, Description, Instal...
CIM_UnitaryComputerSystem           {SetPowerState}      {Caption, Description, Instal...
Win32_ComputerSystem                {SetPowerState, R... {Caption, Description, Instal...
CIM_ComputerSystemResource          {}                   {GroupComponent, PartComponent}
CIM_ComputerSystemMappedIO          {}                   {GroupComponent, PartComponent}
CIM_ComputerSystemDMA               {}                   {GroupComponent, PartComponent}
CIM_ComputerSystemIRQ               {}                   {GroupComponent, PartComponent}
Win32_ComputerSystemProcessor       {}                   {GroupComponent, PartComponent}
CIM_ComputerSystemPackage           {}                   {Antecedent, Dependent}
Win32_ComputerSystemProduct         {}                   {Caption, Description, Identi...
Win32_NTLogEventComputer            {}                   {Computer, Record}

Note  If you try to use a wildcard character for the Classname parameter of the Get-CimInstance cmdlet, an error message returns because the parameter design does not permit wildcard characters.

Finding WMI class methods

If you want to find WMI classes related to processes that contain a method that begins with the letters term*, you use a command similar to the following:

PS C:\> Get-CimClass -ClassName *process* -MethodName term*

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_Process                       {Create, Terminat... {Caption, Description, Instal...

To find all WMI classes related to processes that expose any methods, you would use the following command:

PS C:\> Get-CimClass -ClassName *process* -MethodName *

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_Process                       {Create, Terminat... {Caption, Description, Instal...
CIM_Processor                       {SetPowerState, R... {Caption, Description, Instal...
Win32_Processor                     {SetPowerState, R... {Caption, Description, Instal...

To find any WMI class in the root/cimv2 WMI namespace that expose a method called Create, use the following command:

PS C:\> Get-CimClass -ClassName * -MethodName create

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_Process                       {Create, Terminat... {Caption, Description, Instal...
Win32_ScheduledJob                  {Create, Delete}     {Caption, Description, Instal...
Win32_DfsNode                       {Create}             {Caption, Description, Instal...
Win32_BaseService                   {StartService, St... {Caption, Description, Instal...
Win32_SystemDriver                  {StartService, St... {Caption, Description, Instal...
Win32_Service                       {StartService, St... {Caption, Description, Instal...
Win32_TerminalService               {StartService, St... {Caption, Description, Instal...
Win32_Share                         {Create, SetShare... {Caption, Description, Instal...
Win32_ClusterShare                  {Create, SetShare... {Caption, Description, Instal...
Win32_ShadowCopy                    {Create, Revert}     {Caption, Description, Instal...
Win32_ShadowStorage                 {Create}             {AllocatedSpace, DiffVolume, ...

Filtering classes by qualifier

To find WMI classes that possess a particular qualifier, use the Qualifier parameter. For example, the following command finds WMI classes that relate to computers and have the SupportsUpdate WMI qualifier:

PS C:\> Get-CimClass -ClassName *computer* -QualifierName *update

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_ComputerSystem                {SetPowerState, R... {Caption, Description, Instal...

The parameters can be combined to produce powerful searches that without using the CIM cmdlets would require rather complicated scripting. For example, the following command finds all WMI classes in the root/Cimv2 namespace that have the Singleton qualifier and also expose a method:

PS C:\> Get-CimClass -ClassName * -QualifierName singleton -MethodName *

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
__SystemSecurity                    {GetSD, GetSecuri... {}
Win32_OperatingSystem               {Reboot, Shutdown... {Caption, Description, Instal...
Win32_OfflineFilesCache             {Enable, RenameIt... {Active, Enabled, Location}

One qualifier that is important to review is the Deprecated qualifier. Deprecated WMI classes are not recommended for use because they are being phased out. By using the Get-CimClass cmdlet, it is easy to spot these WMI classes. This technique is shown here:

PS C:\> Get-CimClass * -QualifierName deprecated

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_PageFile                      {TakeOwnerShip, C... {Caption, Description, Instal...
Win32_DisplayConfiguration          {}                   {Caption, Description, Settin...
Win32_DisplayControllerConfigura... {}                   {Caption, Description, Settin...
Win32_VideoConfiguration            {}                   {Caption, Description, Settin...
Win32_AllocatedResource             {}                   {Antecedent, Dependent}

By using this technique, it is easy to find association classes. The following command finds all of the WMI classes in the root/cimv2 WMI namespace that relate to sessions. In addition, it looks for the Association qualifier. Luckily, you can use wildcard characters for the qualifier names; and therefore, the following command uses assoc* instead of typing out association.

PS C:\> Get-CimClass -ClassName *session* -QualifierName assoc*

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_SubSession                    {}                   {Antecedent, Dependent}
Win32_SessionConnection             {}                   {Antecedent, Dependent}
Win32_LogonSessionMappedDisk        {}                   {Antecedent, Dependent}
Win32_SessionResource               {}                   {Antecedent, Dependent}
Win32_SessionProcess                {}                   {Antecedent, Dependent}

One qualifier you should definitely look for is the Dynamic qualifier. This is because it is unsupported to query Abstract WMI classes. Therefore, when looking for WMI classes, you will want to ensure that at some point you run your list through the Dynamic filter. In the following command, three WMI classes return that are related to time:

PS C:\> Get-CimClass -ClassName *time

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_CurrentTime                   {}                   {Day, DayOfWeek, Hour, Millis...
Win32_LocalTime                     {}                   {Day, DayOfWeek, Hour, Millis...
Win32_UTCTime                       {}                   {Day, DayOfWeek, Hour, Millis...

By adding the query for the qualifier, the appropriate WMI classes are identified. One class is abstract, and the other two are dynamic classes that could prove to be useful. In the following script, first the Dynamic qualifier is used, and then the Abstract qualifier appears:

PS C:\> Get-CimClass -ClassName *time -QualifierName dynamic

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_LocalTime                     {}                   {Day, DayOfWeek, Hour, Millis...
Win32_UTCTime                       {}                   {Day, DayOfWeek, Hour, Millis...

PS C:\> Get-CimClass -ClassName *time -QualifierName abstract

   NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                        ---------------      ------------------
Win32_CurrentTime                   {}                   {Day, DayOfWeek, Hour, Millis...

Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

22 Jan 21:37

PowerTip: Rename Network Adapter with PowerShell

by The Scripting Guys

Summary:  Use Windows PowerShell to rename the net adapter.

Hey, Scripting Guy! Question How can I use Windows PowerShell and Windows 8 to rename my network adapter?

Hey, Scripting Guy! Answer Use the Get-NetAdapter function to retrieve the specific network adapter and
          pipe the results to the Rename-NetAdapter function:

Get-NetAdapter –Name Ethernet | Rename-NetAdapter –NewName MyRenamedAdapter

22 Jan 21:31

Your guide to App-V 5.0 application publishing and client interaction

by J.C. Hornbeck

GearsWe just published a new guide designed to help both new and experienced users of Microsoft Application Virtualization (App-V) gain a better understanding of how the App-V 5.0 SP2 client processes packages and presents them to users. It provides details around typical client operations with important locations for data storage, how the publishing refresh process works and the available integration points with the local operating system. Topics discussed in the paper include:

  • App-V Files and Data Storage Locations
  • Package Registry
  • App-V Package Store Behavior
  • Roaming Registry and Data
  • App-V Client Application Lifecycle Management
  • Integration of App-V Packages
  • Dynamic Configuration
  • Side by Side Assemblies
  • Client Logging

You can get all the details and a download link here:

App-V 5 SP2 Application Publishing and Client Interaction

J.C. Hornbeck | Solution Asset PM | Microsoft GBS Management and Security Division

Get the latest System Center news on Facebook and Twitter:

clip_image001 clip_image002

System Center All Up: http://blogs.technet.com/b/systemcenter/
System Center – Configuration Manager Support Team blog: http://blogs.technet.com/configurationmgr/
System Center – Data Protection Manager Team blog: http://blogs.technet.com/dpm/
System Center – Orchestrator Support Team blog: http://blogs.technet.com/b/orchestrator/
System Center – Operations Manager Team blog: http://blogs.technet.com/momteam/
System Center – Service Manager Team blog: http://blogs.technet.com/b/servicemanager
System Center – Virtual Machine Manager Team blog: http://blogs.technet.com/scvmm

Windows Intune: http://blogs.technet.com/b/windowsintune/
WSUS Support Team blog: http://blogs.technet.com/sus/
The AD RMS blog: http://blogs.technet.com/b/rmssupp/

App-V Team blog: http://blogs.technet.com/appv/
MED-V Team blog: http://blogs.technet.com/medv/
Server App-V Team blog: http://blogs.technet.com/b/serverappv

The Forefront Endpoint Protection blog : http://blogs.technet.com/b/clientsecurity/
The Forefront Identity Manager blog : http://blogs.msdn.com/b/ms-identity-support/
The Forefront TMG blog: http://blogs.technet.com/b/isablog/
The Forefront UAG blog: http://blogs.technet.com/b/edgeaccessblog/

15 Jan 13:57

Links from our System Center User Group meeting in Stockholm 14/1 – 2014

by Jörgen Nilsson

Here are the links from mine and Stefan’s (http://cmtrace.com) session “Configuration Manager Community Jewels” that we presented at the System Center User Group meeting in Stockholm 14/1 -2014. There are so many great community tools out there, it would be impossible to even find them all even more to list them all.

Thanks to everyone attending for making it a great event and a special thanks to Wally Mead for spreading some Configuration Manager love.

Installation:

PowerShell Deployment Toolkit: http://gallery.technet.microsoft.com/PowerShell-Deployment-f20bb605

Johan Arwidmark Configuration Manager 2012 R2 Hydration Kit: http://www.deploymentresearch.com/Research/tabid/62/EntryId/113/The-Hydration-Kit-for-ConfigMgr-2012-R2-is-available-for-download.aspx

ConfigMgr 2012 R2 Prerequisites Installation tool: http://www.scconfigmgr.com/2014/01/14/configmgr-2012-r2-prerequisites-installation-tool-new-version-1-2-1-has-been-released/

OS Deployment:

Configuration Manager Driver grabber / injector: http://gallery.technet.microsoft.com/ConfigMgr-Driver-Injector-aae7d17d

Computer Naming RIS Style: http://www.itx-solutions.nl/2012/12/sccm2012ce/

Microsoft Deployment Toolkit 2013: http://www.microsoft.com/en-us/download/details.aspx?id=40796

Niall Brady Bitlocker Frontend HTA: http://www.niallbrady.com/2013/01/18/the-cm12-bitlocker-frontend-hta/

Operations:

Configuration Manager Client Center: https://sccmclictr.codeplex.com/documentation

Configuration Manager 2012 r2 toolkit: http://www.microsoft.com/en-us/download/details.aspx?id=36213

PowerShell Right-Click tools: https://psrightclicktools.codeplex.com/

Rick Houchins’ SCCM Right Click Tools ConfigMgr 2007/2012: http://myitforum.com/myitforumwp/2012/09/21/sccm-rctools/

Huge inventory script: http://www.david-obrien.net/2013/06/20/huge-powershell-inventory-script-for-configmgr-2012/

Configuration Manager inbox monitor: http://wmug.co.uk/wmug/b/r0b/archive/2013/08/28/new-tool-configmgr-inbox-monitor.aspx

Client Push Manager: http://wmug.co.uk/wmug/b/r0b/archive/2013/08/26/new-tool-client-push-manager.aspx

Health Check Script: http://thedesktopteam.com/blog/raphael/sccm-2012-r2-healthcheck-toolkit-pre-beta-version/

Ola Hallengren SQL Maintenance: http://ola.hallengren.com/

SCCM Client Actions Tool PowerShell Edition aka PoshCAT: http://blog.coretech.dk/kaj/sccm-client-actions-tool-powershell-edition-aka-poshcat/

RegKeyToMof: http://myitforum.com/cs2/files/folders/proddocs/entry152945.aspx

Configuration Manager 2012 R2 Visio stencils: http://gallery.technet.microsoft.com/System-Center-2012-R2-e4279188

Application Management:

PowerShell Application deployment toolkit: https://psappdeploytoolkit.codeplex.com/

Coretech Shutdown Tool: http://blog.coretech.dk/kea/new-version-of-the-coretech-shutdown-tool/

Application Approvals: http://blogs.technet.com/b/neilp/archive/2012/09/25/configuration-manager-application-request-notification-and-approval-solution.aspx

Coretech Application e-mail approval: http://blog.coretech.dk/kea/coretech-application-e-mail-approval-tool/

15 Jan 13:51

xDscResourceDesigner Module –PowerShell Desired State Configuration Resource Kit

by PowerShell Team
The xDscResourceDesigner module is a part of the DSC Resource Kit, which is a collection of DSC related artifacts produced by the PowerShell Team. This module makes DSC resource creation a breeze and ensures that all the rules, which a DSC resource must conform to, are met.

Created by: PowerShell Team
Published date: 1/14/2014
13 Jan 14:36

Custom PowerShell Objects and Performance Revisited

by Boe Prox

Way back in my earlier days of blogging (Sept 2010), I wrote an article (I recommend you check this one out for more information regarded some of the older styles of custom object creation) that talked about the performance differences between a few different ways that you can create a custom PowerShell object.

At that time we were rocking PowerShell V2 and enjoying all of the great benefits that were being brought to us. Fast forward to now and we are sitting at V4 and have a new way to create a custom PowerShell object in [pscustomobject]. What this brings us is a way to finally have the speed benefits of doing PSObject…

New-Object PSObject -Property @{
Name = 'Boe'
Number = 1
ID = 007
}

…with the ability of keeping everything in the order we specify like when we use the Select-Object method:

$Object = '' | Select-Object Name, Number, ID
$Object.Name = 'Boe'
$Object.Number = 1
$Object.ID = 007

Another method which was discussed was the use of Add-Member to create objects:

$Object = New-Object PSObject
$Object | Add-Member -MemberType NoteProperty -Name Name -Value Boe -PassThru |
Add-Member -MemberType NoteProperty -Name Number -Value 1 -PassThru |
Add-Member -MemberType NoteProperty -Name ID -Value 007 -PassThru

The New Stuff

I won’t really dive any deeper into these as you can view that old blog post to catch up on the rest of that stuff, but what I will do is show off [pscustomobject] as well as take all of these for a spin again and show off the performance differences between these 4 contenders.

[pscustomobject] is pretty simple to use:

[pscustomobject]@{
    Name= 'Boe'
    Number = 1
    ID = 007
}

The best part is that it keeps its order and is pretty quick as well. Just how quick is it? Well, sit back and check out the stats when compared to the other methods. If you have read the previous blog entry, you will see that Add-Member was by far the slowest method while Select-Object and New-Object PSObject were neck and neck in speed with PSObject pulling ahead slightly for the win.

After I initially published this article, I had some suggestions on other items to include in my testing. The are New-Object PSObject –Property ([ordered@{}) and $prop=[ordered]@{};[pscustomobject]$prop (labeled [pscustomobject][ordered]). Both of these output the same type of ordered object, meaning that the order that you supply the data in the hash table is the same order that it will display on the console.

Keep in mind that this produces the exact same output as if you would use [pscustomobject] by itself.

image

So how will these newcomers compare with everything else? Let’s find out!

The Approach

If you saw the previous blog where I talk about performance, you noticed that I had a script that helped to make the determination as to what was the fastest approach. Well, this script was not exactly the best written script and had a lot of manual things going on. I’ve updated my script to make it easier to add the number of cycles (basically the number of “systems” to run against), the number of properties to have in the custom object and finally the number of times to repeat each operation. The script is available to download from the link at the end of this article if you are interested in running it yourself.

The Results

I started out at running against 10 “systems” (cycles) while creating the following sets of objects (1,5,10,25,50,100) and repeated this 5 times. I then upped the cycles to the following values and ran against each one to record the time it took each type to complete: 50,100,500,1000,5000,10000. The first list of graphs will show you everything at its own scale, meaning that the highest time for each cycle will be the max on the graph. Because this doesn’t always tell the whole store, I also included a second set of graphs that show the highest value recorded during the entire time spent running the scans (the 10000 cycle scan had the highest time taken). At the beginning, you really won’t see much of anything but as the cycles go on, you can see which approach becomes slower and slower.

So with all of that out of the way, let me show the first set of graphs that show the results of my tests.

image

image

image

image

image

image

 

Both [pscustomobject] and the [pscustomobject][ordered] approach were the fastest ones in PowerShell and for the most part are interchangeable (assuming that you are running V3/4, of course). Add-Member is definitely the slowest approach, much like it was when I first ran this test. The rest of the bunch were back and forth as far as which ones were faster at any given moment in time.  As I said previously, these numbers are all scaled to their respected highest time. The graphs below will show the scale from the 10000 Cycle run which had the highest time returned.

image

image

image

 

image

image

image

This shows that in the same scale as 10000 cycles, the level of difference in performance doesn’t really come into play until you are running against 500 systems. Of course, various outside conditions such as network latency and system performance come into play as well, but you get the idea.

Much like the tests I ran back in 2010, Select-Object and New-Object PSObject are practically neck and neck and really come down to your preference of having your properties come out in the order that they were coded (Select-Object) or having a very slight and much better looking (from a coding style) approach (PSObject).

I hope you enjoyed this article and found the information useful when it comes time to make a decision what method you wish to take. My personal take is that if you are running V3/4, then you really should be using [pscustomobject] unless you have a need to add to an existing object or add some other levels of properties to an object in which Add-Member should be used at the cost of performance. While the [pscustomobject][ordered] was on par with [pscustomobject], they are the same thing and if you want to save an extra line of code, you should look at just using [pscustomobject]@{} by itself. But in the end, it is up to you to decide what you feel may be the right choice based on your requirements.

Download Script

Technet Script Repository


Tagged: custom objects, performance, Powershell
09 Jan 15:36

Deploying System Center Using the PowerShell Deployment Toolkit

by Damian Flynn

What's in a name? With the name "PowerShell Deployment Toolkit," (PDT) one would be forgiven for assuming that this utility is some silly script created to assist those of us who are still living with some aging versions of Windows Client OS in our environment and and who need to get PowerShell deployed to these nodes.

PowerShell Deployment Toolkit (PDT) and System Center 2012 SP1/R2

Don't get the wrong impression. The PowerShell Deployment Toolkit is a work of art and a mandatory utility for anyone who has the slightest requirement for getting an environment installed for System Center 2012 SP1 or R2. Locked behind this unassuming name is a super powerful set of three PowerShell scripts and two XML files that will forever change how you will prepare your lab, proof of concept – or, for the very accomplished – potentially your production installations.

At the time of this writing, PDT is floating at version 2.5.2708 and fully supports the deployment of both System Center 2012 SP1 and R2. It also will cater for building out an Active Directory Domain if you prefer to lab your installations – and of course you will require a SQL Server, which the toolkit is more than willing to also accommodate for you.

Getting the Bits

The first step in getting going with PDT is to take a quick trip to the Technet Gallery, where you will find the latest and greatest versions of the PowerShell Deployment Toolkit. Download this archive, mark it as unblocked, and extract the content.

You are going to need a working folder, which you will also share out once everything is prepared. This working folder will be home to the PDT files and also to all the media we need for deploying a System Center Installation. As you begin your folder will look similar to my sample (shown below).

PowerShell Deployment Toolkit installation

Now, before we get too excited, the first thing i like to do is edit the Variable.xml file and change the value for the Download setting to point to my working folder (this is also a good reason for sharing the folder), which in my case will look as follows.

PowerShell Deployment Toolkit installation

I am configuring the tool to download on the fly to $SystemDrive\Temp, and then place the files in S:\Workspace\PDT\Installer as the final destination. to define these I am using the following parameters

<Variable Name="TempPath" Value="$SystemDrive\Temp" />
<Variable Name="Download" Value="S:\Workspace\PDT\Installer" />

I have a third working parameter set called Source Path. This is is the UNC, or mount point, connected to the initial share I created for the PDT folder. It is utilized when I choose to execute the PDT Installer from a VM, which is a member of the target environment I am deploying. For example, my environment's domain controller.

Downloading the Components

Our next task is to grab all the different components which will be required for installing our Windows Server System Center environment. PDT will assist us for the vast majority of these, reaching out to Microsoft and downloading all the necessary components. However, there are a few that PDT will not be automatically downloading, so we must take care of these by hand.

To determine which components PDT will not download, we can upload the workflow.xml file into a variable. As this is pure XML, we can easily create a simple query that will identify the components we must download. The following sample will complete this procedure for us.

$Workflow = [XML] (Get-Content ".\Workflow.xml")
$Workflow.Installer.Installables.Installable | foreach {If (! $_.Download.URL) { Write-Host $_.Name }}

The results of this query will be similar to the following.

PowerShell Deployment Toolkit download variable

Ignoring both Integrations and Prerequisites from this list, we can quickly determine that both Windows Server 2012 and Windows Server 2012 R2, along with the components of System Center 2012 R2, will need to be manually downloaded. These can be located on the Microsoft servers and placed in their respective folders in the PDT Installer tree. You can use the following as a reference.

\\MYServer\S$\WORKSPACE\PDT
├───Installer
│   ├───Download
│   │   ├───Prerequisites
│   │   │   └───ADK81
│   │   ├───SharePoint2010Module
│   │   ├───SharePoint2010SP2Foundation
│   │   ├───SQLServer2008R2
│   │   ├───SQLServer2012.en
│   │   │   └───SQLFULL_x64_ENU
│   │   ├───SystemCenter2012R2
│   │   │   ├───AppController
│   │   │   │    └SW_DVD5_Sys_Ctr_2012_R2_MultiLang_AppCont_MLF_X19-18210.ISO.ISO
│   │   │   ├───ConfigurationManager
│   │   │   │    └SW_DVD5_Sys_Ctr_2012_R2_MultiLang_ConfMgr_ML_MLF_X19-18215.ISO
│   │   │   ├───DataProtectionManager
│   │   │   │    └SW_DVD5_Sys_Ctr_Datacenter_2012_R2_MultiLang_DPM_MLF_X19-22687.ISO
│   │   │   ├───OperationsManager
│   │   │   │    └SW_DVD5_Sys_Ctr_2012_R2_English_OpsMgr_MLF_X19-18307.ISO
│   │   │   ├───Orchestrator
│   │   │   │    └SW_DVD5_Sys_Ctr_2012_R2_MultiLang_Orch_MLF_X19-18211.ISO
│   │   │   ├───ServiceManager
│   │   │   │    └SW_DVD5_Sys_Ctr_2012_R2_MultiLang_SvcMgr_MLF_X19-18213.ISO
│   │   │   └───VirtualMachineManager
│   │   │             └SW_DVD5_Sys_Ctr_2012_R2_MultiLang_VMM_MLF_X19-18212.ISO
│   │   ├───SystemCenter2012SP1
│   │   │   ├───AppController
│   │   │   ├───ConfigurationManager
│   │   │   ├───DataProtectionManager
│   │   │   ├───IntegrationPacks
│   │   │   ├───OperationsManager.en
│   │   │   ├───Orchestrator
│   │   │   ├───ServiceManager
│   │   │   └───VirtualMachineManager
│   │   ├───WindowsServer2012
│   │   │    └9200.16384.WIN8_RTM.120725-1247_X64FRE_SERVER_EVAL_EN-US-HRM_SSS_X64FREE_EN-US_DV5.ISO
│   │   └───WindowsServer2012R2
│   │        └9600.16384.WINBLUE_RTM.130821-1623_X64FRE_SERVER_EVAL_EN-US-IRM_SSS_X64FREE_EN-US_DV5.ISO
│   ├───Prerequisites
│   ├───Sharepoint2012Module

After you have placed each of the resources in the respective location, you can proceed to use the PDT utility called Downloader.ps1 to grab all the other components, after which it will then process and extract both the components it downloaded as well as the items you manually placed so that they are prepared for installation.

Getting Started

Once you have completed this, you are pretty much ready to get started. In our next post we will take a closer look at the variables.XML file, and walk through the procedure of editing this file to automatically deploy your first System Center component.

07 Jan 13:06

Top Five 2013 PowerShell Scripts in Script Center Repository

by The Scripting Guys

Summary: The Scripting Wife reveals the top five Windows PowerShell scripts from the Script Repository for 2013.

Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife is here again today to tell us the five most popular scripts that were downloaded from the Script Center Repository in 2013.

Hello all. I have taken the time to gather more stats for you. Here are the top five most popular scripts that were downloaded from the Script Center Repository in 2013:

  1. Get Active Directory User Last Logon
    This script provides Active Directory administrators with the ability to quickly and easily identify the exact last log-on date and time for a user account.

  2. Simple PowerShell function to send email
    This is a simple Windows PowerShell function that sends email. There are a series of variables (for example, $subject) that can be used as parameters.

  3. Exchange 2010 Public Folder Replication Report
    This script will generate a report of the Exchange Server 2010 public folder environment and replication status. It returns the replication status of each folder and general information, such as the total size and count of Public Folders and Top 10 Largest Folders.

  4. Get-RemoteProgram Get list of installed programs on remote or local computer
    This script generates a list by querying the registry and returning the installed programs of a local or remote computer.

  5. Create bulk AD User and mailbox from CSV file
    This script creates an Active Directory account from a CSV file and the Exchange Server 2010 mailbox.

Thanks, all!

   ~Scripting Wife

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

06 Jan 12:58

Using PowerShell to Back Up Group Policy Objects

by The Scripting Guys

Summary: Guest blogger, Ian Farr, talks about using Windows PowerShell to back up Group Policy Objects.

Microsoft Scripting Guy, Ed Wilson, is here. Today I am happy to welcome back a recent new guest blogger, Ian Farr. Here is what Ian had to say about himself:

I started out writing UNIX shell scripts to automate simple tasks. Then as a Windows IT pro, I discovered VBScript, and it ignited a passion for automation. Over the years, I've used batch files, KiXtart, JScript, HTAs, Perl, JavaScript, and Python. I love solving problems with scripts, and I've written code for several large enterprise environments. I now work as a premier field engineer at Microsoft, teaching Windows PowerShell and helping my customers with their own scripts.

The challenge

A customer recently asked about backing up Group Policies Objects (GPOs), “Can the Windows PowerShell Group Policy cmdlets mirror our production GPOs to our test environment?“

Almost. The cmdlets aren’t enough, however.  Information has to be collected by using several techniques. I decided to produce a demonstration Windows PowerShell script to share with the community. In fact, I wrote two code samples—one to back up and one to import. Keeping the script functions separate increases their reuse potential.

The backup                           

“To begin at the beginning…”

I work out my script flow before I write any code. Understanding the structure and content saves time and effort. I started by listing what GPO information to capture:

  • Group Policy settings
  • Delegation
  • Security filtering
  • Scope-of-management (SOM)
  • Block inheritance
  • Enforced
  • Link enabled
  • Link order
  • WMI filters
  • IP security policies

Let’s look at the relevant sections of the script to see how to get the information.

Group Policy settings, delegation, security filtering

The Backup-GPO cmdlet, from the Group Policy PowerShell module, captures GPO settings, delegation, and security filtering information. The script assigns objects that are returned by the cmdlet to $Backups for later use:

$Backups = Backup-GPO -All -Path $SubBackupFolder -Domain $DomainFQDN -Comment "Scripted backup created by $env:userdomain\$env:username on $(Get-Date -format d)"

The Backup-GPO parameters:

  • All does what you’d expect. It tells the cmdlet to back up all GPOs in the domain.
  • Path determines where the backup is saved. The $SubBackupFolder variable is made up of the backup folder name (in the format Year_Month_Day_HourMinuteSecond) and the backup target path (a parameter passed at script execution), for example:

Image of folder

  • Domain is also a script parameter (the target domain), and it must be a fully qualified domain name (FQDN).
  • Comment is a string that is associated with the backup. In this instance, it combines output from Windows environment variables and the Get-Date cmdlet. It shows who created the backup and when, for example:

“Scripted backup created by CONTOSO\FarrI on 22/10/2013”

Scope-of-management and block inheritance

So what’s scope-of-management (SOM)? SOM refers to a site, domain, or organizational unit where a GPO is linked. The Group Policy cmdlets won’t capture the SOM details needed, but the Group Policy Management (GPM) COM interfaces can. The Group Policy Management Console (GPMC) provides access to these interfaces.

A GPM COM object has the ability to automate many GPMC functions. The backup API that is exposed is also used by the Backup-GPO cmdlet, and it shares the same limitations. A different interface is needed for SOM details.

Here’s how to create a GPM COM object:

$GPM = New-Object -ComObject GPMgmt.GPM

GPM constants provide easy access to incredibly useful functionality. To obtain the GPM constants:

$Constants = $GPM.getConstants()

For more information about constants, see:

Now tell the GPM object to reference the target domain. Notice the constants:

$GpmDomain = $GPM.GetDomain($DomainFQDN,$Null,$Constants.UseAnyDc)

Start a parent loop and process each backed-up GPO by using the GPO GUID to instantiate an object as $GPO:

ForEach ($Backup in $Backups) {

 

        #Get the GPO GUID for our target GPO

        $GpoGuid = $Backup.GpoId

       

        #Instantiate an object for the relevant GPO using GPM

        $GPO = $GpmDomain.GetGPO("{$GpoGuid}")

Next, some SOM-specific search criteria for the current $GPO:

$GpmSearchCriteria.Add($Constants.SearchPropertySOMLinks,$Constants.SearchOpContains,$GPO)

Put that criteria to use:

$SOMs = $GpmDomain.SearchSOMs($GpmSearchCriteria)

Open a child loop to process the SOMs for the current GPO and assign the distinguished name and inheritance status of the SOM to variables:

  ForEach ($SOM in $SOMs) {

 

                #Capture the SOM Distinguished Name

                $SomDN = $SOM.Path

          

                #Capture Block Inheritance state

                $SomInheritance = $SOM.GPOInheritanceBlocked

Enforced, link enabled, link order

As part of the child loop, the Get-GPInheritance cmdlet obtains enforced, link enabled, and link order details:

            $GpoLinks = (Get-GPInheritance -Target $SomDN).GpoLinks

Because the cmdlet and its parameter are in parenthesis, they are evaluated first by Windows PowerShell. A Microsoft.GroupPolicy.Som object is returned. The contents of the GpoLinks property of this object is then stored in $GpoLinks.

The next loop is the grandchild of the parent loop. We cycle through each of the potential values in $GpoLinks and check that the display name associated with the value matches that of the current GPO. This check is necessary because there could be other GPOs associated with the SOM.

            $GpoName = $GPO.DisplayName

                ForEach ($GpoLink in $GpoLinks) {

                    If ($GpoLink.DisplayName -eq $GpoName) {

                        #Capture the GP link status

                        $LinkEnabled = $GpoLink.Enabled

 

                        #Capture the GP precedence order

                        $LinkOrder = $GpoLink.Order

 

                        #Capture Enforced state

                        $LinkEnforced = $GpoLink.Enforced

 

                    }   #End of If ($GpoLink.DisplayName -eq $GpoName)

                }   #End of ForEach ($GpoLink in $GpoLinks)

Enforced, link enabled, and link order details are now assigned to variables. Before closing the child loop, add the newly populated variables for each SOM to a string, and add the string to an array:

[Array]$SomInfo += "$SomDN`:$SomInheritance`:$LinkEnabled`:$LinkOrder`:$LinkEnforced"

}   #End of ForEach ($SOM in $SOMs)...

The format of the strings in the $SOMInfo array will aid reporting and importing.

"$SomDN:$SomInheritance:$LinkEnabled:$LinkOrder:$LinkEnforced"

For example:

Image of command output

WMI: GPOs with filters

A WMI filter refines the GPO scope by using computer attributes. If the filter returns True, the policy is applied. Each GPO can have only one WMI filter. Capturing WMI filter information is a two part process. Get-GPO is used to obtain the path of the filter:

$WmiFilter = (Get-GPO -Guid $GpoGuid).WMiFilter.Path

For example:

Image of command output

The path is then split at the quotation marks to get the filter name:

$WMiFilter = ($WmiFilter -split "`"")[1]

For example:

Image of command output

One object to rule them all

One incredibly useful feature of Windows PowerShell is the ability to create custom objects. Here a new object is created for the current GPO by using the [PSCustomObject] type declaration and a hash table of properties. The $SOMInfo array is assigned to the SOMs property of the hash table.

        $GpoInfo = [PSCustomObject]@{

                BackupGuid = $BackupGuid

                Name = $GpoName

                GpoGuid = $GpoGuid

                SOMs = $SomInfo

                DomainDN = $DomainDN

   WmiFilter = $WmiFilter

                       

        }   #End of $Properties…       

The new object is then added to a parent array. When the parent loop is finished, $TotalGPOs contains objects for all backed-up GPOs.

 [Array]$TotalGPOs += $GpoInfo

}   #End of ForEach ($Backup in $Backups)...

WMI: The filters

The custom objects in $TotalGPOs have details of any linked WMI filters. To pull the WMI filters out of Active Directory, use Get-ADObject:

     $WmiFilters = Get-ADObject -Filter 'objectClass -eq "msWMI-Som"'

                            -Properties msWMI-Author, msWMI-ID, msWMI-Name, msWMI-Parm1, msWMI-Parm2

The -Filter parameter targets objects that match the WMI filter object class ‘msWMI-Som’. The –Properties parameter asks for attributes that are not returned by default. The attributes returned have key WMI filter details that are used by the import script, for example:

 Image of command output

The properties are:

  • msWMI-Author: The account that created the filter.
  • msWMI-ID: The filter ID (corresponds to the Active Directory object name).
  • msWMI-Name: The “human-readable” filter name.
  • msWMI-Parm1: The filter description.
  • msWMI-Parm2: The WQL statement used by  the filter.
    For more information, see Querying with WQL.

IP security policies

Here’s a self-imposed limitation— IP security policies aren’t backed up. However, just like WMI filters and the Active Directory Group Policy container, IP security policies are stored in the system container of a domain partition. This time, the schema object class to filter on is ipsecPolicy. Over to you, my capable friends!

Image of menu

Export and report

Time to export and report. First, use the Export-CliXML cmdlet to export the custom objects to GpoDetails.xml ($CustomGpoXML):

            $TotalGPOs | Export-Clixml -Path $CustomGpoXML

Why? The exported (serialized) objects are easily imported (deserialized) from the XML file, so we instantly get our objects and properties back, albeit without the original methods. The import script in Part 2 of this series uses the XML file.

This process is repeated for any WMI filters that are retrieved from Active Directory ($WmiXML points to WMiFIlters.xml):

$WmiFilters | Export-Clixml -Path $WmiXML

Next, we need a “human-readable” CSV report. Each report line contains the GPO name, the GPO GUID, and a cell for each string in the SOMs property, for example:

Image of report

Here’s how the report is populated. Start a parent loop to process each object contained in the $TotalGPOs array, and start building a string to add to the CSV report:

ForEach ($CustomGPO in $TotalGPOs) {    

        $CSVLine = "`"$($CustomGPO.Name)`",`"{$($CustomGPO.GPOGuid)}`","

Expand the SOMs property and loop through any values returned. Each value found is appended to the CSV line:

        $CustomSOMs = $CustomGPO | Select-Object -ExpandProperty SOMs

        ForEach ($CustomSOM in $CustomSOMs) {

            #Append the SOM path to our CSV line

            $CSVLine += "`"$CustomSOM`","

       }   #End of ForEach ($CustomSOM in $CustomSOMs)...

When the SOMs loop is finished, write the fully constructed CSV line to the report:

                        Add-Content -Path $SOMReportCSV -Value $CSVLine

            }   #End of ForEach ($CustomGPO in $TotalGPOs)...

The parent loop is closed when the CSV report has an entry for every custom GPO object.

Migration tables

The script has a –MigTable switch. What’s it for?

Domain-specific data, such as UNC paths, users, or groups, might need translating for the domain import.  The GPMC allows you to create a Migration Table, where a source value can be matched to a destination value. Can you automate the creation of a migration table? Of course!

The Group Policy cmdlets can’t be used, so over to the GPMC COM interfaces. We can access the CreateMigrationTable method of the GPM COM object:

$MigrationTable = $GPM.CreateMigrationTable()

Domain-specific information from each GPO is added to the migration table as part of a loop. The ProcessSecurity constant evaluates security on the backed-up GPO:

       ForEach ($BackedUpGPO in $BackedUpGPOs) {

            $MigrationTable.Add($Constants.ProcessSecurity,$BackedUpGPO)

       }   #End of ForEach ($BackedUpGPO in $BackedUpGPOs)...

The file is then saved as “MigrationTable.migtable,” and it is defined in $MigrationFile:

$MigrationTable.Save($MigrationFile)

Note  After the migration table is created, the Destination names have to be manually updated, for example:

Image of report

And that concludes Part 1. We have a backup of all the GPOs in the production domain. We’ve captured additional, important GPO information. We’ve produced a “human-readable” CSV report, and we exported our custom GPO objects and WMI filters to XML. We may have even created a migration table.

You can see the entire script in the Script Center Repository: Comprehensive Group Policy Backup Script.

Please join me tomorrow when I’ll discuss how to mirror this information to a test environment.

~Ian

Thank you, Ian, for sharing your time and knowledge.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

01 Jan 17:08

Desired State Configuration (DSC) Resource Kit Wave-1

by Ravikanth

Are you looking at writing your own DSC resources? Have you been following our DSC articles? DSC is the exciting new feature in Windows PowerShell 4.0. To add to this excitement, PowerShell … [visit site to read more]