blog.powershell.no

On Windows PowerShell and other admin-related topics

Introducing the PowerShell Network Adapter Configuration module

For a Windows administrator, working with network adapters is a common task. A common approach many companies use is configuring servers with static IP addresses (IPv4) and clients using DHCP. The IP address is just one of many properties of a network adapter, as we also have properties like subnet mask, default gateway, DNS server search order and so on. Configuring these properties is usually performed during the initial setup of a computer, either manually or by a deployment mechanism.

The configuration of a network adapter is mostly static, however, from time to time some properties might need to be changed. In example the subnet on a network is expanded to meet new requirements, and thus the subnet mask property must be updated on computers not using DHCP. Another scenario is the setup of new DNS servers, with a decision not to keep the existing DNS servers` IP addresses. I recently faced the last scenario, where several hundred servers configured with static IP addresses needed to have their DNS configuration updated. Using Windows PowerShell the task can be automated, even if we need to perform the task on 10, 100 or 1000 servers. However, the more computers a script is run against, the more important it is to implement proper error handling and logging to keep track of which computers is updated.

The above task is just one of many potential tasks for configuring a network adapter. Since I was unable to find any existing PowerShell module/library for working with network adapters on Windows systems, I decided to create a project on Codeplex:

 

The PowerShell Network Adapter Configuration module

The PowerShell Network Adapter Configuration (PSNetAdapterConfig) module is a PowerShell module for working with network adapters on Windows-based computers. The module is using Windows Management Instrumentation (WMI) to retrieve and configure properties of network adapters.

The current release of the module makes use of the following WMI-classes:

The module currently contains 4 functions:

  • Get-DNSServerSearchOrder – get the DNS client settings for a network adapter (the property name is DNSServerSearchOrder)
  • Get-NetConnectionId – get the name of a network adapter (the property name is NetConnectionId)
  • Set-DNSServerSearchOrder – change the configured DNSServerSearchOrder. This function contains two parameter sets, one for replacing the current DNSServerSearchOrder property value, the other for adding/removing IP addresses from the current value
  • Set-NetConnectionId – change the name of a network adapter. In example, change the name from “Local Area Connection” to “Server VLAN 42”

I will add functions to the module when I find time, but I also hope that people in the community will contribute by either improving the existing functions, providing suggestions or creating new functions.

When downloading a PowerShell module from the internet (typically a zip-file), beginners often get into problems because they don`t know that the file first needs to be unblocked (Right-click the zip-file->Properties->Unblock). To overcome this challenge I created a Windows installer (MSI) file which is easy to install and does not need to be unblocked:

image

The default install path is %userprofile%\Documents\WindowsPowerShell\Modules, and the user have the option to override the module path.

The installer was created using Windows XML Installer (Wix), based on Chad Miller`s blog-post Building A PowerShell Module Installer.

When the module is installed, we can use Import-Module to import the module, and Get-Command to list the available commands:

image

As we can see there is also an alias for each of the commands (functions).

By using Get-Help we can see available parameters along with their descriptions, as well as several examples:

image

The functions supports both ValueFromPipeline and ValueFromPipelineByPropertyName, which means we can leverage the PowerShell pipeline. Have a look at example 3 on the above image to see how computers can be retrieved from Active Directory using Get-ADComputer, and then piped directly into the Set-DNSServerSearchOrder function.

The functions outputs PowerShell objects, which mean we can use regular PowerShell techniques to work with the data, in example converting the objects to HTML or CSV. I typically use Export-Csv to output the data to CSV-files which in turn can be converted to Excel spreadsheets:

image

 

The functions is using a try/catch construct, using the following logic:

  1. Ping the computer, if unsuccessful the property “Connectivity” on the output object is set to “Failed (ping”)
  2. Connect to the computer using WMI, if unsuccessful the property “Connectivity” on the output object is set to “Failed (ping”)
  3. The property “Connectivity” on the output object is set to “Successful” if step 1 and 2 succeeds
  4. Retrieve or change the applicable properties using WMI

When working with a large number of computers we can use Sort-Object in PowerShell to filter the output objects based on the Connectivity property, or the sorting functionality in Microsoft Excel if the output objects is piped to a CSV-file.

 

The final example I will show is using the Set-NetConnectionId function. On a test-computer we have a network adapter named “Local Area Connection 5”:

image

Using Set-ConnectionId we can specify the subnet for which network adapter to perform the change on (the above network adapter has an IP address of 192.168.56.10) and specify the new name of the network connection:

image

When the command has run we can see that the connection name for the adapter has changed:

image

One additional feature that might be included to this function is the ability to provide a hash-table with a mapping of subnets and NetConnectionIds, which will make it easy to create a consistent naming convention for network adapters.

As a final note, all functions has a Logfile parameter, allowing us to log error message to the specified file.

 

Requirements

  • Windows PowerShell 2.0
  • ICMP (ping) and WMI firewall openings from the computer running the module to the target computers
  • Administrator permissions on the target computers

To avoid the firewall requirements, a workaround is running the functions from a PowerShell script locally on target computers using a software distribution product like System Center Configuration Manager.
Another option is to run the functions over PowerShell remoting.

 

Download and feedback

The module is available for download on the Codeplex project site http://psnetadapterconfig.codeplex.com. Please use the Discussions and Issue Tracker sites on the project site to report bugs and feature requests.

 

Resources

The functions is too long to walkthrough in a blog-post, so I will direct you to the following resources to get started working with advanced functions and modules in PowerShell:

An Introduction to PowerShell Modules by Jonathan Medd.

An Example ScriptModule and Advanced Function by Don Jones.

Ten tips for better PowerShell functions by James O`Neill.

Maximize the reuse of your PowerShell by James O`Neill.

November 22, 2011 Posted by | Remote Management, Scripting, Server management, Windows PowerShell | , , , , | Leave a Comment

Hyper-V: How to unbind a physical NIC from a Virtual Switch using WMI and PowerShell

If you`re not already familiar with networking in Microsoft Hyper-V I would recommend you to have a look at this whitepaper from Microsoft, which described how networking works in Hyper-V.

The following solution will describe a problem which might occur when configuring virtual networks in Hyper-V. Consider the following scenario:

  • You`re about to configure a new external virtual network in Hyper-V using Hyper-V Manager remotely from another computer. This is a common scenario when working with the Core edition of Windows Server 2008/2008 R2.
  • When selecting the physical NIC to bind to the new virtual network, you choose the adapter which you are remotely connecting to the Hyper-V host through.

What happens in this scenario is that the Virtual Switch Management Service is binding the external Ethernet port for the selected NIC to the Microsoft Windows Virtualization network subsystem. What normally should happen next is that the converted Ethernet port should be bound to the new virtual switch you are creating. However, this never happens since the NIC you are remotely managing the Hyper-V host through is no longer available in the parent operating system. This leaves the NIC in an “orphaned” state, since you cannot use the NIC in the parent operating system, and it`s not in use by any virtual networks.

To resolve this issue, whether using the full GUI version or the Core version of Windows Server, you need to manually unbind the the Ethernet port. There is an UnbindExternalEthernetPort available on the Msvm_VirtualSwitchManagementService WMI class, which is fully documented in this article on MSDN.

To invoke the WMI method we can use Windows PowerShell. To ease the procedure I`ve created a PowerShell function you can use if you ever come into the need for manually unbinding an external Ethernet port in Hyper-V:

 

Function Select-List
{
    Param   ([Parameter(Mandatory=$true  ,valueFromPipeline=$true )]$InputObject, 
             [Parameter(Mandatory=$true)]$Property)

    begin   { $i= @()  }
    process { $i += $inputobject  }
    end     { if ($i.count -eq 1) {$i[0]} elseif ($i.count -gt 1) {
                  $Global:counter=-1
                  $Property=@(@{Label=“ID”; Expression={ ($global:Counter++) }}) + $Property
                  format-table -inputObject $i -autosize -property $Property | out-host
                 $Response = Read-Host “Select NIC to unbind”
                  if ($response -gt “”) { 
                        $I[$response] 
                  }
              }
            }
}

function Remove-HVExternalEthernetPort {

$ExternalEthernetPort = Get-WMIObject -class “Msvm_ExternalEthernetPort” -namespace “root\virtualization” | Select-List -Property name

$HVSwitchObj = Get-WMIObject -class “MSVM_VirtualSwitchManagementService” -namespace “root\virtualization”

if ($ExternalEthernetPort) {
$HVSwitchObj.UnbindExternalEthernetPort()
}
else {
throw “An error occured. Choose a valid ExternalEthernetPort from the provided list”
}

}

Note: The Select-List function is a modified version of the Select-List function available in the PowerShell Management Library for Hyper-V available on CodePlex (see link below).

You can either paste the function into a PowerShell session or save it into ps1-file and dot source it. When done you can invoke the function like this:

image

When you`ve entered the index number for the NIC you want to remove, a return value of 0 indicates the operation succeeded. Any other value indicates an error (look at the previous mentioned MSDN-article for more information).

 

More resources on managing Hyper-V using PowerShell

PowerShell Management Library for Hyper-V – this is an excellent PowerShell module for managing Hyper-V available on CodePlex

System Center Virtual Machine Manager 2012: Scripting

System Center Virtual Machine Manager 2008 R2: Scripting

Hyper-V WMI Using PowerShell Scripts

Script: Determining Virtual Switch Type Under Hyper-V

August 30, 2011 Posted by | Hyper-V, Hyper-V R2, Scripting, Virtualization, Windows PowerShell | , , | Leave a Comment

Getting starting with Cisco UCS PowerShell Toolkit

Cisco – widely known as a networking infrastructure vendor – entered the blade server market in 2009. Their offering is called Unified Computing System, described by Gartner as a fabric-enabled, enterprise-class platform with good integration of networking, virtualization, management tools and storage. On the 2011 Gartner Magic Quadrant for Blade Servers they`re defined as a visionary vendor, and it will be interesting to see if they can challenge the 3 leaders Dell, IBM and HP.

The Cisco Unified Computing System is quite different from traditional blade systems, in that the server profiles (so called service profiles) is independent from the physical blade servers. An example to describe what this means is that a physical blade server might fail and be replaced, while the server profile keeps unique ID`s like MAC addresses, World Wide Names (WWN`s) and so on. If using boot from SAN rather than local disk drives, physical interaction is not required to get the system back online if a spare blade server is available.

 

The UCS core components

  • Blade Chassis – Blade server enclosure
  • Cisco UCS Manager – Embedded into the Fabric Interconnect. Provides management capabilities
  • Cisco UCS fabric interconnect – Provides networking (Ethernet/Fibre Channel) and management for connected blades and chassis`
  • Fabric Extenders – Provides connection between the interconnect fabric and the blade enclosures

A photo showing the Cisco Unified Computing System architecture is available here (cisco.com). In regards of management, all aspects of Cisco UCS can be managed through an XML API. This makes it possible for 3rd parties to offer management solutions, and integration with other products. An example of a 3rd party product is the Cisco UCS Iphone/Ipad application for managing and monitoring the system. Links for more information on the management model and the XML API is available in the resources section in the bottom of this article.

 

Cisco UCS PowerShell Toolkit

Based on a customer request from an early adaptor, Cisco provided PowerShell support for managing their UCS product through the XMP API. With the Microsoft automation strategy in mind, this was an excellent choice. It will make integration into products like System Center Orchestrator (formerly Opalis) very easy, and the also make the product attractive for enterprises. The PowerShell administration tool is available as a module part of the Cisco UCS PowerShell Toolkit.

A great way to learn using the Cisco UCS PowerShell Toolkit is downloading the Cisco UCS Emulator. This is a virtual machine image which can be imported into VMware Player or VirtualBox. When the VM is up and running you can access both the UCS Manager (http URL is shown when the VM has started) and the XML API. A great feature is that you can import the configuration from a production UCS to simulate administration changes in a lab environment.

Next, you can download the latest versions of both the Cisco UCS PowerShell Toolkit (aka UCSMPowerTool) and the PowerShell Toolkit User Guide from this website.

The installer will by default put the files in %programfiles%\Cisco\UCSMPowerToolkit:

image

CiscoUCSPS.dll is the assembly which can be imported as a module in Windows PowerShell 2.0 and later. You can either double-click LaunchUCSPS.bat or invoke StartUCSPS.ps1 from an existing PowerShell session to get started. Alternatively you can use Import-Module from an existing PowerShell session like this:
Import-Module “C:\Program Files (x86)\Cisco\UCSMPowerToolkit\CiscoUCSPS.dll”

I would suggest rather than installing to the Program Files folder (which requires administrative privileges), that Cisco generates a module manifest and install the module to the default PowerShell module directory (C:\Users\<username>\Documents\WindowsPowerShell\Modules).

When the module is imported we can use Get-Command with the –Module parameter to list all command inside the CiscoUCSPS module:

image

The current version of the module contains 149 cmdlets, so all commands are not shown in the above screenshot.

The first thing we need to do is connect to an instance of the UCS Manager. If using the Cisco UCS Emulator you can view the management  IP address when the virtual machine has started:

image

We then use the Connect-UCSM cmdlet to connect to the UCS Manager:

image

The default credentials for the UCS Emulator is config/config.

Next we can start exploring cmdlets like Get-Blade and Get-Vlan. Note that by default the cmdlets outputs a lot of information for each object, so I`ve picked out a few properties to show using Format-Table:

image

Going further it`s easy to automate things like adding VLAN and assigning it to a vNIC template:

image

 

Although the PowerShell coverage isn`t 100% yet, it`s possible to administer all aspect of the UCS directly through the XML API from PowerShell using the Invoke-XmlCommand cmdlet.

 

Resources

Cisco Unified Computing

A Platform Built for Server Virtualization: Cisco Unified Computing System

Cisco Unified Computing Forums

Automating Cisco UCS Management with Windows PowerShell

PowerScripting Podcast – Josh Heller from Cisco on UCS and PowerShell

Cisco UCS Manager XML API Programmer’s Guide

Cisco UCS Manager API Management Information Model

Cisco Developer Network: Unified Computing

Managing your Cisco UCS from an iPhone or iPad

July 23, 2011 Posted by | Scripting, Virtualization, Windows PowerShell | , , | 2 Comments

Adding printer drivers from a print server using Windows PowerShell

Managing printer drivers in a Remote Desktop Services (formerly Terminal Services) environment can be a challenge for administrators. There are many ways to ease this challenge, including third party solutions such as ThinPrint and UniPrint. When “thick” drivers are used on the RDS servers, all printer drivers must be installed locally on every server. Citrix XenApp has a printer driver replication feature which makes it possible to distribute printer drivers from a source server to one or more destination servers in a farm.

There might be situations where none of the mentioned solutions can be used for various reason, i.e. financial costs. A common way to solve this problem is to map all printer connections from a specified print server using administrative credentials during the initial setup of each RDS server. This solves the problem, but it can be time consuming as all printers that uses the same driver is being installed. Even though the driver is already installed on the local computer, it takes some time to process each printer connection.

I recently faced this challenge, as the installation of all printer connections from a few specified print servers took 30-40 minutes using a legacy script. I then wrote an advanced function in PowerShell to make the procedure more effective. This was accomplished by installing a printer connection only for unique printer drivers.
An example: A print server has 500 shared printer objects, while there is only 10 unique printer drivers. It would make more sense to add a printer connection (in order to install the driver) to 10 printer objects rather than 500, given the time consumed by installing a printer connection.

The function is available for download from here.

Sample usage and output:

image

 

image

There is a switch option added to the function called Clean. If this parameter is specified the function will also remove all mapped printer connections for the current user.

The function doesn’t`t provide any log options. However, it produces PowerShell objects, so it would be easy to pipe the output to a file.
An example on how to export the output objects to a csv-file:

image

But what about printer drivers added to the print servers after the function is run on an RDS server? One way to solve this could be adding the PowerShell function to a script-file which is set up as a scheduled task to run i.e. once a day on every RDS server.  If the scheduled task is set up using Group Policy Preferences, it will be automatically created on every new RDS server that is added later on. Beside scheduling the task to run at specified intervals, the print server administrator may also invoke the scheduled task remotely on every RDS server whenever a new print driver is added to a print server. The details on how to do this is previously described in this blog-post.

Since the function might be run several times on the same computer, it also checks if the driver to be installed is already in place on the local computer. This means that after the first run, only printer drivers added to the print server after the first run is actually installed. This makes the script more effective, and depending on the number of shared printer objects on the specified print server, it shouldn’t`t run for many seconds.

Coming back to the before mentioned example (~600 printer objects, ~50 unique drivers) where it took 30-40 minutes to install printer drivers from a print server, when using the Add-PrinterDriver PowerShell function the execution ran for 4 minutes. After the first run, subsequent executions ran for  20 seconds.

July 3, 2011 Posted by | Print management, Remote Desktop Services, Scripting, Terminal Services, Windows PowerShell, Windows Server 2008, Windows Server 2008 R2 | , , , , | 3 Comments

Use Windows PowerShell to get antivirus product information

Windows Security Center has been available in Windows client operating systems since Windows XP SP2. This is a useful feature for monitoring the overall for security status for the system, including antivirus, antimalware and firewall protection. In situations no monitoring software like System Center Operations Manager is in place to monitor the security health on client computers, one option is to use Windows Management Instrumentation. There is a WMI namespace called root\SecurityCenter2 which exposes information from the Windows Security Center, like what antivirus product is installed on the system.

I`ve created PowerShell function to query computers for information on what antivirus is installed as well as the current status for antivirus definitions and real-time protection:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
function Get-AntiVirusProduct {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)
]
[
Alias('name')]
$computername=$env:computername
)

$AntiVirusProduct = Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct  -ComputerName $computername

#Switch to determine the status of antivirus definitions and real-time protection.
#The values in this switch-statement are retrieved from the following website: http://community.kaseya.com/resources/m/knowexch/1020.aspx

switch ($AntiVirusProduct.productState) {
"262144" {$defstatus = "Up to date" ;$rtstatus = "Disabled"
}
   
"262160" {$defstatus = "Out of date" ;$rtstatus = "Disabled"
}
   
"266240" {$defstatus = "Up to date" ;$rtstatus = "Enabled"
}
   
"266256" {$defstatus = "Out of date" ;$rtstatus = "Enabled"
}
   
"393216" {$defstatus = "Up to date" ;$rtstatus = "Disabled"
}
   
"393232" {$defstatus = "Out of date" ;$rtstatus = "Disabled"
}
   
"393488" {$defstatus = "Out of date" ;$rtstatus = "Disabled"
}
   
"397312" {$defstatus = "Up to date" ;$rtstatus = "Enabled"
}
   
"397328" {$defstatus = "Out of date" ;$rtstatus = "Enabled"
}
   
"397584" {$defstatus = "Out of date" ;$rtstatus = "Enabled"}
default {$defstatus = "Unknown" ;$rtstatus = "Unknown"
}
    }

#Create hash-table for each computer
$ht = @{}
$ht.Computername = 
$computername
$ht
.Name = $AntiVirusProduct.displayName
$ht.ProductExecutable = $AntiVirusProduct.pathToSignedProductExe
$ht.‘Definition Status’ = 
$defstatus
$ht
.‘Real-time Protection Status’ = $rtstatus

#Create a new object for each computer
New-Object -TypeName PSObject -Property $ht

}

 

Sample output:

image

The root\SecurityCenter2 namespace isn`t documented on MSDN, so it`s hard to find information on the properties and methods we find in the different classes in the namespace.

The productstate property of the AntiVirusProduct class is exposed as a integer value, which needs to be converted to a hexadecimal value. Then the different bytes in the value contains information in regards to definition updates and real-time protection. More information on this is available here. I haven`t found a complete reference to all possible values, the best I could find is available here.

The above function outputs Windows PowerShell objects, so it`s possible to filter the output i.e. based on the “Definition Status” property.  The computername parameter also supports value from pipeline to make it easy to get the computers to query from i.e. Active Directory without using a foreach construct. A few examples:

001
002
003
004
005
006
#Get antivirus product information for all computers in the specified OU/container
Import-Module ActiveDirectory
Get-ADComputer -SearchBase "CN=Computers,DC=contoso,DC=local" -Filter * | Select-Object -ExpandProperty name | Get-AntiVirusProduct

#Filter using Where-Object to get all computers where the Definition State is not "Up to date"
Get-AntiVirusProduct -computer (Get-Content computers.txt) | Where-Object {$_.‘Definition Status’ -notlike ‘Up to date’}

 

The root\SecurityCenter2 namespace is available on Windows Vista SP1 and above. Windows Security Center is not available on server operatingsystems, meaning that the root\SecurityCenter2 namespace also isn`t available. In Windows XP SP2 the namespace is called root\SecurityCenter, but the properties are not the same as in root\SecurityCenter2. It`s possible to get the function work on Windows XP, but you would need to customize it to match the properties available in the root\SecurityCenter namespace.

I would encourage you to add error handling before using this function in a production environment, i.e. adding a test to check if the remote computer is available and allowing RPC-communication. If you would like to explore the other classes in the root\SecurityCenter2 namespace for working with firewall and antispyware products, you can start by exploring the available classes like this: Get-WmiObject -Namespace root\SecurityCenter2 -List

June 12, 2011 Posted by | Desktop management, Scripting, Windows 7, Windows PowerShell, Windows Vista | , | Leave a Comment

Enable Persistent Mode for Cluster Resource Groups using the PowerShell Failover Clustering module

In Failover Clustering in Windows Server 2008 R2, Persistent Mode is intended to allow resource groups to come online on the node which an admin last moved them to. This setting is enabled by default when a virtual machine is created with Failover Cluster Manager. If you create virtual machine via System Center Virtual Manager this setting is not enabled.

By default, cluster roles have this setting disabled, except for Hyper-V virtual machine cluster roles, which have this enabled by default. This setting is useful when the cluster is shutdown and later started, in order to better distribute the resources across the nodes and allow them to come online faster, as they were likely spread across the nodes before the cluster was offlined. Otherwise, all the resources will attempt to restart on the first nodes which achieve quorum and compete for resources. This only applies to a group if it did not failover after being placed by the administrator. If a group has failed over since the last administrator placement, it is brought online on the node which the administrator last move it to.

Reference and more info regarding the Auto Start, Persistent Mode and Group Wait Delay features is available on the Clustering and High-Availability blog.

Auto Start can be enabled/disabled in bulk by marking all Cluster Resource Groups in Failover Cluster Manager and selecting “Enable auto start”/”Disable auto start”.

For Persistent Mode the only available option in Failover Cluster Manager is to right click each Cluster Resource Group and selecting/de-selecting the checkbox for “Enable persistent mode”:

image

To change this setting for all Cluster Resource Groups in an automated fashion you can use the Failover Cluster module for PowerShell, which I wrote an introduction to here.

Here is an example on how you can do this:

001
002
003
004
005
006
007
Import-Module FailoverClusters
$clustergroups = Get-ClusterGroup -Cluster cluster01.domain.local
foreach ($clustergroup in $clustergroups) {
#To enable persistent mode: x To disable persistent mode: 4294967295
$clustergroup.DefaultOwner=x
}

Although you can change the Auto Start setting in bulk in Failover Cluster Manager you might also want to do this in an automated fashion:

001
002
003
004
005
006
007
Import-Module FailoverClusters
$clustergroups = Get-ClusterGroup -Cluster cluster01.domain.local
foreach ($clustergroup in $clustergroups) {
#To enable Auto Start: 1 To disable Auto Start: 0
$clustergroup.Priority=1
}

You can also change the Group Wait Delay cluster-wide property from the PowerShell Failover Clustering module, how to do this is explained in the above referenced blog-post from the Clustering and High-Availability blog.

For the next version of System Center Virtual Machine Manager I would expect that Persistent Mode is enabled by default, since Microsoft do recommend customers to enable this setting.

Update 08.12.2011: The value of the DefaultOwner property for configuring Persistent Mode is the number of the node you want to be the default owner. In example a value of 1 means the first node in the cluster.

June 3, 2011 Posted by | Failover Clustering, Hyper-V, Hyper-V R2, Scripting, Windows PowerShell, Windows Server 2008 R2 | , | 2 Comments

Script Template Add-on for PowerGUI Script Editor

As a best practice, most script authors adds a header to their scripts containing some basic information like the script name, the author and version history.

Some commercial script editors, like Idera`s PowerShell Plus, contains script-templates to make this easier. PowerGUI is another commercial editor, available both in a free and Pro version. This product doesn`t contain any script templates by default, however it`s easy to extend the product with needed functionality by building Add-ons. I`ve created an add-on named Script Template, available here.

When creating a new document in the PowerGUI Script editor, the following template is automatically inserted when the Add-on is loaded:

image

The easiest way to install the Add-on is by using Tools->Find Add-ons Online:

image

Search for “script template” and then press “Install”.

If you want to customize the template you can open the file \Documents\WindowsPowerShell\Modules\Add-on.ScriptTemplate\Add-on.ScriptTemplate.psm1 and modify the following section:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
$template = @"
###########################################################################
#
# NAME:
#
# AUTHOR: $env:USERNAME
#
# COMMENT:
#
# VERSION HISTORY:
# 1.0 $((get-date).ToShortDateString()) – Initial release
#
###########################################################################

"@

 

Note that the first new document automatically created when opening the PowerGUI Script Editor won`t get pre-filled with the script template header, since the Script Template Add-on isn`t loaded yet. However, all consecutive new documents will get the template automatically.

A similar Add-on is available here for PowerShell ISE, created by PowerShell MVP Ravikanth Chaganti.

If you`re interested in creating your own Add-ons for the PowerGUI Script Editor, have a look at this excellent tutorial created by Kirk Munro and Dmitry Sotnikov.

March 12, 2011 Posted by | Scripting, Windows PowerShell | , | Leave a Comment

DFS-R Health Report for SYSVOL

Distributed File System Replication (DFS-R) was introduced as a replacement for File Replication Service (FRS) in Windows Server 2008, and was further enhanced in Windows Server 2008 R2. When your domain functional level are set to Windows Server 2008, you have the option to migrate SYSVOL-replication from the deprecated FRS to the new and more reliable DFS-R service. A major advantage of using DFS-R over FRS is that FRS copies the whole file when a change are made, while DFS-R only copies the changed bits. This and further details are discussed here. I`ve also included some links in the resource section below on how to perform an FRS to DFS-R migration.

Included in the Windows Server 2008 and Windows Server 2008 R2 are the DFS Management-console as well as several command-line tools for administering DFS. A great built-in feature in these tools is the diagnostic reports.

This is available in the DFS Management-console:

image

As well as from the DfsrAdmin.exe command-line tool:

image

Using this feature we can generate an HTML-report containing a great overview of the replication health for the SYSVOL replication group:

image

Any errors and warnings will be shown with detailed explanations. In addition we can view general information and statistics i.e. regarding free diskspace on the domain controllers, bandwith savings and so on (click on the thumbnail to view):

image

Since the reporting feature are available from the DfsrAdmin.exe command-line tool, it makes it easy to set up a script as a scheduled task that also sends the generated report via e-mail i.e. every morning. I`ve published a simple PowerShell-script to accomplish this which is available here.

Resources

SYSVOL Replication Migration Guide: FRS to DFS Replication (Word-version available here)

Verifying File Replication during the Windows Server 2008 DFSR SYSVOL Migration

DFSR SYSVOL Migration FAQ

Configuring DFSR to a Static Port

FRS to DFSR Migration Tool (not for SYSVOL migration)

December 30, 2010 Posted by | Active Directory management, DFS-R, Scripting, Windows PowerShell, Windows Server 2008, Windows Server 2008 R2 | | 2 Comments

Retrieve number of mailboxes per database in Exchange Server 2010

Mailbox databases in Exchange Server 2010 doesn`t contain any information regarding the numbers of mailboxes stored in them. A common approach to retrieve this information is using the Exchange Management Shell.

Two examples

 1: #Example 1

 

 2: (Get-MailboxDatabase) | ForEach-Object {Write-Host $_.Name (Get-Mailbox -Database $_.Name).Count}

 

 1: #Example 2

 

 2: (Get-MailboxDatabase) | Select-Object Name,@{Name="Number of users";Expression={(Get-Mailbox -Database $_.name).Count}}

 

Either of these works fine if you want to get the number of mailboxes quick and dirty. However, in larger environments, these one-liners may run for a while.

I did a quick measurement using the Measure-Command cmdlet; Example 1 ran for 36 seconds and example 2 ran for 30 seconds. The environment I ran this in got 5 mailbox databases and approximately 1300 mailboxes.

When running these as one-liners from the Exchange Management Shell, or as part of a scheduled task, the performance might not be an issue.

A colleague of mine was using the Cmdlet Extension Scripting Agent to provision new mailboxes to the mailbox database with the least number of mailboxes in it. In this scenario the performance is key. To achieve better performance, we used an LDAP-query using System.DirectoryServices.DirectorySearcher.

Get-MDBMailboxCount function

I created a PowerShell function to retrieve the number of mailboxes per mailbox database using the DN of a mailbox database as an argument.

 function Get-MDBMailboxCount ([string]$DN) {

 

$Searcher = New-Object System.DirectoryServices.DirectorySearcher

 

$Searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://$(([system.directoryservices.activedirectory.domain]::GetCurrentDomain()).Name)")

 

$Searcher.Filter = "(&(objectClass=user)(homeMDB=$DN))"

 

$Searcher.PageSize = 10000

 

$Searcher.SearchScope = "Subtree"

 

$results = $Searcher.FindAll()

$returnValue = $results.Count

#dispose of the search and results properly to avoid a memory leak
 $Searcher.Dispose()
 $results.Dispose()

return $returnValue

 

}

 

A problem we stumbled upon was that wildcards didn`t seem to work on the homeMDB-attribute, so we couldn`t use *Mailbox Database Name* for this value.

When looking up on MSDN, it turned out that wildcards are not supported on LDAP DN`s:

For queries that include attributes of DN syntax in a filter, specify full distinguished names. Wildcards (for example, cn=John*) are not supported.

That`s the reason for the function taking DN as an argument, and not the name of a mailbox database.

The function runs the query against the current domain, and hence you don`t need to specify a domain for the LDAP-query.

Back to the performance part, I now ran Measure-Command against the following one-liner:

 1: (Get-MailboxDatabase) | ForEach-Object {Write-Host $_.Name (Get-MDBMailboxCount -DN $_.DistinguishedName)}

 

This time the performance was 3,7 seconds, almost 10x faster. Actually, using a foreach-loop instead of Foreach-Object also makes it slightly faster; 3,5 seconds. You can read up on the difference between these two approaches here.

Get-MDBMailboxCount script

Having the Get-MDBMailboxCount function, I also decided to create a script using this function, which generates a CSV-file.

The script uses a foreach-loop to go through each database in the Exchange-organization, and then creates a custom object for each database containing the name and number of mailboxes. The custom objects are added to an array which can be used for other things like determining the smallest/largest database. You could also use this information to generate graphs like I showed in this blog-post.

Note that I`ve only tested the above against Exchange Server 2010. I suppose it also should work against Exchange Server 2007, if someone can verify this it would be nice if you could leave a comment below.

Update 04.08.2011: The function has been updated  to avoid a memory leak when the function is called multiple times. Thanks to Weston McNamee for the tip (see his comment below).

November 21, 2010 Posted by | Exchange Server 2010, Exchange Server management, Scripting, Windows PowerShell | | 13 Comments

Follow

Get every new post delivered to your Inbox.

Join 45 other followers