Manage RDS RemoteApp with Windows PowerShell
In Windows Server 2008 R2, Remote Desktop Services (formerly Terminal Services) includes a provider for managing RDS using Windows PowerShell. You may find more information along with some examples in this article on Microsoft TechNet.
One of the many things you can manage this way is the new RemoteApp-feature introduced with Windows Server 2008. In Windows Server 2008 R2, this feature got enhanced by the addition of User Assignment and Web Single Sign-On capabilities. These new features makes it possible for more and more customers to consider RDS without additional products like Citrix. One benefit using Citrix are more flexible application-management, since an published application may be available from a new farm member without adding each application manually.
Let`s look at a given example: You got a farm with 16 RDS-servers, and you`re leveraging the RemoteApp-feature. For each server in the farm, you must manually set up all applications in RemoteApp-manager after they`re installed. Although there is an export/import-feature in the GUI, many customers require no manual interaction in the server provisioning process. By the addition of the new PowerShell-provider for RDS, this is now possible in RemoteApp using scripting as part of either server provisioning or Group Policy.
For the average Windows sysadmin, I imagine that managing RemoteApp using the RDS PowerShell provider might be a bit tedious. To make this a little easier I`ve created a Windows PowerShell module for working with RDS RemoteApp, available from here.
This module contains the following functions:
- Get-RDSRemoteApp
- Export-RDSRemoteApps
- Import-RDSRemoteApps
- New-RDSRemoteApp
- Remove-RDSRemoteApp
The functions let you administer the same application attributes as the graphical RemoteApp Manager:
- Displayname
- Alias
- Command-line arguments
- RD Web Access availability
- User Assignment
Installing the RDSRemoteApp module
Download and unzip RDSRemoteApp.zip in the following location: %userprofile%\Documents\WindowsPowerShell\Modules\RDSRemoteApp
Alternatively you may save the module in any of the folders in the $Env:PSMODULEPATH variable.
Using the RDSRemoteApp module
First we`ll have a look at the RemoteApp Manager application-list in the lab-environment:
Start Windows PowerShell on the RDS-server and import the module (you will need to run PowerShell with Administrative privileges):
Since I`ve leveraged the built-in help capabilities in Windows PowerShell v2 Advanced Functions, I`ll show the usage of the functions with a few screenshots from the help:
Get-RDSRemoteApp
New-RDSRemoteApp
Remove-RDSRemoteApp
Export-RDSRemoteApps
Import-RDSRemoteApps
Sample usage for export/import:
Be aware that there are several other RDS settings that may be managed using the PowerShell provider, this module only leverages the RemoteApp functionality. If someone want to create a module for managing other aspects of RDS, feel free to include my RDSRemoteApp module. And as always, suggestions for improvements and new functionality are more than welcome.
Manage Windows Update installations using Windows PowerShell
In most domains Windows Update are controlled by Group Policy and Windows Server Update Services (WSUS). For client computers, it`s common to download and install updates automatically. For servers, we want to control the installation of Windows Updates inside a scheduled maintenance window, and hence the Windows Update settings are configured not to automatically install updates.
If there are a few servers to manage, it won`t be that time consuming to log on to each server with Remote Desktop and do the Windows Update installations manually. In larger environments however, this won`t be an option, it must be automated in some way. While enterprise environments typically invest in a commercial product like BigFix for patch management, this might be overkill or too expensive for environments smaller than an enterprise.
To manage Windows Update in an automated way we can access the Windows Update Agent API using a COM-object called Microsoft.Update.Session. Using the New-Object cmdlet in Windows PowerShell, it`s easy to work with this COM-object. Based on this COM-object and portions of James O`Neill`s functions for managing Windows Update, I`ve written a PowerShell-script called Invoke-WindowsUpdate.
This script is intended to be used to download and install Windows Updates on servers. It runs like expected when invoked from a local computer, however, invoking the script using PowerShell Remoting like I was planning turned out to be problematic: Invoke-Command -ComputerName ServerA -FilePath ‘C:\ps-scripts\Windows Update\Invoke-WindowsUpdate.ps1′
This will return the following error message:
Exception calling “CreateUpdateDownloader” with “0″ argument(s): “Access is denied. (Exception from HRESULT: 0×80070005 E_ACCESSDENIED))”
This issue doesn`t seem to be related to PowerShell, as there are several others reporting the same problem in other languages like VBScript.
The common workaround is to schedule the script to run as a scheduled task running as SYSTEM. I`ve chosen to use this approach and to use PowerShell Remoting to invoke the scheduled task to run the script. An example:
$servers = Get-Content ‘C:\ps-scripts\Windows Update\BulkA.txt’
foreach ($server in $servers) {
Invoke-Command -Computer $server -ScriptBlock {schtasks /run /tn “PowerShell – download and install Windows Updates”}
}
To create the scheduled task I would recommend you to use Group Policy Preferences.
A few sample screenshots from my lab setup:
Although it`s possible to invoke the script on all servers in the domain at once using i.e. the Active Directory-module for PowerShell to get the server names, I would recommend to break down the installations in several bulks. This way you can control that all domain controllers doesn`t go offline at the same time and so on.
As you can see in the script it`s also possible to enable reporting to e-mail or file (HTML) to a central location, in addition to control whether the servers should reboot if required.
Planned improvements include nicer reports, Windows Update settings in the reports and if possible make the script work without having to use scheduled tasks. Suggestions for other improvements are always welcome.
Backing up Group Policy Objects using Windows PowerShell
A best practice in domain environments are backing up the Group Policy Objects regularly. Even though a GPO may be restored by restoring a system state backup from a domain controller to an alternate location, and then copy the contents from the deleted GPO to a new GPO to restore the settings, this may be a hazzle since it`s not pretty straightforward. It also requires you to restart the domain controller affected in Directory Services Restore Mode.
PowerShell MVP Don Jones has written a good article on this topic, available here.
For those of you who may not want to do GPO restore the hard way, or buy a commercial third party product, I would encourage you to schedule regular GPO backups using the Windows PowerShell Group Policy-module available in Windows Server 2008 R2, as well as RSAT in Windows 7.
To accomplish this, I`ve written a small script which backs up all modified GPO`s in the specified timespan. I would generally recommend to have the script run once a day, thereby setting the timespan-variable to the last 24 hours. The script are called Backup-ModifiedGPOs.ps1, and available from here.
All Group Policy Objects modified in the specified timespan are backup up to the specified backup path.
Also, an HTML-report are created for each GPO-backup, with the unique backup GUID as part of the filename. This way you can easily see what settings each backup contains.
When restoring a GPO, you must first note the GUID of the backup you want to restore. Then you can restore the GPO by using the Restore-GPO cmdlet in the Group Policy-module. Sample usage:
Administrators who feels more comfortable working with the GUI, may use the Group Policy Management Console to do the restore.
The following procedure from the Group Policy Planning and Deployment Guide on Microsoft TechNet describes how to accomplish the restore operation from the GUI:
To view the list of GPO backups
- In the GPMC console tree, expand the forest or domain that contains the GPOs that you want to back up.
- Right-click Group Policy Objects, and the click Manage Backups.
- In the Manage Backups dialog box, enter the path to the location where you stored the GPO backups that you want to view. Alternatively, you can click Browse, locate the folder that contains the GPO backups, and then click OK.
- To specify that only the most recent version of the GPOs be displayed in the Backed up GPOs list, select the Show only the latest version of each GPO check box. Click Close.
Using the GPMC to restore GPOs
You can also restore GPOs. This operation restores a backed-up GPO to the same domain from which it was backed up. You cannot restore a GPO from a backup into a domain that is different from the GPO’s original domain.
To restore a previous version of an existing GPO
- In the GPMC console tree, expand Group Policy Objects in the forest or domain that contains the GPOs that you want to restore.
- Right-click the GPO that you want to restore to a previous version, and then click Restore from Backup.
- When the Restore Group Policy Object Wizard opens, follow the instructions in the wizard, and then click Finish.
- After the restore operation completes, a summary will state whether the restore succeeded. Click OK.
To restore a deleted GPO
- In the GPMC console tree, expand the forest or domain that contains the GPO that you want to restore.
- Right-click Group Policy Objects, and then click Manage Backups.
- In the Manage Backups dialog box, click Browse, and then locate the file that contains your backed-up GPOs.
- In the Backed up GPOs list, click the GPO that you want to restore, and then click Restore.
- When you are prompted to confirm the restore operation, click OK.
- After the restore operation completes, a summary will state whether the restore succeeded. Click OK. Click Close.
Important: Since Group Policy links are stored on the Organizational Unit objects in Active Directory, this information are not backup up and also not restore. However, the HTML backup-reports contains this information, so you may manually re-link the GPO to the correct OU(s).
Also note that WMI filters and IPSec policies are not backed up by the backup feature in the Group Policy Management Console. For more information on how to manage these items, see the before mentioned Group Policy Planning and Deployment Guide.
Dynamic Remote Desktop Connection Manager connection list
Microsoft recently released a free tool for managing multiple remote desktop connections called “Remote Desktop Connection Manager”.
A sample screenshot:
There are several nice features, such as “Connect group” which lets you connect to all servers in a group at once:
On the “Group Properties” you may set common settings for all connections in the group, like logon credentials:
Further, there are group properties for RDS Gateway (formerly TS Gateway), display settings, local resources and so on.
There are several applications for remote desktop connections on the market, and some of them got these settings as a per server setting. It`s nice to be able to group servers and configure common settings.
Dynamically creating the connection list
When you work in larger environments with hundreds, maybe thousands of servers, setting up each connection manually isn`t an option.
Since Remote Desktop Connection Manager stores the config-files in xml-files, it`s rather easy to create dynamic config-files for a domain using Windows PowerShell. I`ve created a script to accomplish this, called New-RDCManFile.ps1, available from here. It uses Microsoft`s PowerShell-module for Active Directory, which is available in Windows Server 2008 R2 and RSAT for Windows 7.
The script does the following:
Creates a template xml-file
Inserts the logged on user`s domain name in the file properties
Inserts the logged on user`s domain name in the group properties
Inserts the logged on user`s username in the logoncredentials section
Inserts the logged on user`s domain name in the logoncredentials section
Retrieves all computer objects from Active Directory with the word “server” in the operatingsystem property
Adds each computer object as a server object
Saves the XML-file to %userprofile%\domain-name.rdg
When done you can open the rdg-file in Remote Desktop Connection Manager. I would recommend you to insert your password in the Group Properties to avoid being asked for credentials for each connection.
Feel free to customize the script to your needs, in example by editing the XML-template to edit the Group Properties. Another customization might be creating a group for each server OU for enhanced overview in larger environments.
If you would rather use Quest`s PowerShell Commands for Active Directory (which works on downlevel operatingsystems like Windows XP and Windows Server 2003), or any other way to retrieve the server names, you may customize this on line 110.
You might also want to schedule the script to run on a regular basis, saving the file to a central location. This way the IT personnel will always have access to the latest version with the most recent servers added.
If you got any further ideas or comments, please let me know in the comments section below.
Script to create a NLB-cluster for Exchange Server 2010
When documenting installations I perform I prefer to refer to scripts whenever possible, since this means less screenshots and a more concise reference.
When deploying Exchange Server 2010 on Windows Server 2008 R2, we have access to the new PowerShell-module for administering NLB. With this in mind I`ve created a script to set up a NLB-cluster for Exchange Server 2010 CAS/Hub-roles in Windows Server 2008 R2.
The script are interactive and will perform the following:
- Ask for input for variables (cluster FQDN, operation mode, etc.)
- Create the new cluster based on the variables provided by the user
- Remove the default port rule
- Add port rules for http, https, POP3, RPC, IMAP4, SMTP, MSExchange RPC and MSExchange Address Book Service
- Ask for the addition of additional nodes. Loops through this procedure until the user answers no
Prerequisites:
- Install the NLB-feature (may be accomplished from the ServerManager module in PowerShell by executing Add-WindowsFeature NLB)
- Configure the NLB NIC`s with the approriate name, IP-address and subnetmask (and disable “Register this connection`s addresses in DNS”)
- Manually add the cluster FQDN to DNS
- Configure static ports for the MS Exchange RPC and MS Exchange Address Book Service (see links in the resource section below)
- Eventually, configure your network switches/routers based on the cluster operation mode you choose
Screenshot:
The script are available from here. In a later revision I`m considering adding support for installing the NLB-feature (I dropped it for now since it could only be offered on the server running the script from, not the additional nodes. This can however be accomplished using PowerShell Remoting), setting the dedicated IP-addresses for the NLB NICs and turn off “Register this connection`s addresses in DNS”.
If you don`t want the interactive experience, replace the “Read-Host” sections with the actual variable values.
Please let me know in the comments below if you have any suggestions for improvements.
Related resources
Exchange Server TechCenter: Understanding Load Balancing in Exchange 2010
Exchange Server TechCenter: Load Balancing Requirements of Exchange Protocols
Microsoft TechNet Wiki: Configuring Static RPC Ports on an Exchange 2010 Client Access Server
Bhargav Shukla (MSFT): Script to configure static ports on Exchange Server 2010
Windows Server TechCenter: Network Load Balancing
Microsoft’s Failover and Network Load Balancing Clustering Team Blog: PowerShell for NLB
Kraft Kennedy: Configuring NLB for Exchange 2010 CAS Load Balancing
Script to spread Exchange mailboxes alphabetically across databases
I recently needed to write a script to spread mailboxes in Exchange Server 2010 alphabetically across databases. In my scenario there were 5 databases, and I used a regex switch in PowerShell to assign each mailbox to the correct database based on the first character in the user`s displayname:
switch -regex ($displayname.substring(0,1))
{
“[A-F]” {$mailboxdatabase = “MDB A-F”}
“[G-L]” {$mailboxdatabase = “MDB G-L”}
“[M-R]” {$mailboxdatabase = “MDB M-R”}
“[S-X]” {$mailboxdatabase = “MDB S-X” }
“[Y-Z]” {$mailboxdatabase = “MDB Y-Z” }
default {$mailboxdatabase = “MDB Y-Z” }
}
The reason for the un-even spreading of letters are that the Norwegian language contains 3 extra letters, and I just assign those as well as other non-letter characters to the last database.
The script are available from here. You may of course adjust the number of databases, the ranges of letters to use, which user attribute to sort against (e.g. lastname) and so on to fit your needs.
Although there are several common approaches to provisioning mailboxes across databases, be aware of the new mailbox provisioning load balancer in Exchange Server 2010. If you don`t specify a database when creating or moving a mailbox, the load balancer will automatically select the database with the least number of mailboxes. Check out this post by Mike Pfeiffer to see this feature in action.
Exchange Server 2010 Cross-Forest migration
In Exchange Server 2010 we can move mailboxes between forests when a forest trust are in place. This can be accomplished using the New-MoveRequest cmdlet from the Exchange Management Shell as well as from the Exchange Management Console. Note that remote mailbox moves from legacy Exchange versions only can be accomplished from the Exchange Management Shell.
Before any move requests can be made there are some preparation that needs to be done in the target forest. The users from the source forest must be created in the target forest as mail-enabled users with some specific attributes. The mandatory attributes in addition to several others are described in this article on the Exchange Server TechCenter.
Microsoft has published a sample script, Prepare-MoveRequest, to assist with the preparation in the target forest. The script will create new mail-enabled users in the target forest with the required attributes from the source forest. While this works quite well, many administrators wants to use alternate methods such as Active Directory Migration Tool (ADMT) or Microsoft Identity Lifecycle Manager (ILM) to preserve additional attributes. Especially SIDHistory and passwords are common.
When these tools are used, the Prepare-MoveRequest script got a parameter named –UseLocalObject which tells the script to convert the local object to the required mail-enabled user. While this might work fine depending on the environment, we`ve seen several administrators reporting problems when using the Prepare-MoveRequest script after ADMT-migration. When the script doesn`t find or match any local user due to some missing attributes it rather creates new mail-enabled users. There are no switch to disable the creation of new users if a local object to use aren`t found. I did a test in a lab-environment trying to use Prepare-MoveRequest with the –UseLocalObject parameter to prepare an ADMT-migrated object. This resulted in a new user being created with some random numbers added to the displayname and samaccountname.
As an alternative to using the Prepare-MoveRequest sample script I`ve created another PowerShell-script named Invoke-MoveRequest, available from here. This script are intended for scenarios where the user objects are already migrated using e.g. ADMT. Note that you must exclude Exchange-attributes when using ADMT, otherwise attributes like msExchHomeServerName which we don`t want to be migrated will come along. Using this script we will migrate the necessary Exchange-attributes.
The script will do the following:
- Copy the attribute Mail from the source object to the target object
- Copy the attribute mailNickname from the source object to the target object
- Copy the attribute msExchMailboxGUID from the source object to the target object
- Set the attribute msExchRecipientDisplayType to –2147483642
- Set the attribute msExchRecipientTypeDetails to 128
- Copy the attribute msExchUserCulture from the source object to the target object
- Set the attribute msExchVersion to 44220983382016
- Copy the attribute proxyAddresses from the source object to the target object
- Set the target objects attribute targetAddress equilent to the source object`s mail attribute
- Set the attribute userAccountControl to 514
- Run the Update-Recipient cmdlet on the target mail-enabled user to set LegacyExchangeDN and other default Exchange-attributes
- Create a new move request
- Enable the target object and unset “User must change password on next logon”
The attributes copied and set are according to the list of mandatory attributes in the TechNet-article mentioned above. The mandatory attributes like DisplayName who not are added to the script are already migrated by ADMT. I also considered adding the LegacyExchangeDN from the target object as an X500 address to the source object`s proxyaddresses to keep mail-flow between the forests after migration, however, it turns out that this are taken care of by the New-MoveRequest cmdlet.
All variables in the “Custom variables”-section on the top of the script must be set before running. The script are set up to process all users in a specified Organizational Unit in the source domain, however, you may customize this for your needs by e.g. using a CSV-file or setup some filtering using the Where-Object cmdlet. You may also copy additional attributes mentioned in the TechNet-article.
The computer you`re running the script from must have the Exchange Management Tools for Exchange Server 2010 and the free Quest PowerShell Commands for Active Directory.
The script needs additional functionality regarding logging and error-handling, I`ll update this post when I`ve done so. Feel free to further enhance the script yourself, and please let me know in the comments below if you have any suggestions.
Installing Exchange Server 2007/2010 Update Rollups
Have you ever tried to install an Exchange Server Update Rollup which ended with an error message?
I recently did some troubleshooting on installing Exchange Server 2010 Update Rollup 3 and picked up some experiences I would like to share, in addition to provide some general guidelines for installing Exchange Update Rollups.
The installation may fail when installing either manually by downloading the installation package or by using Windows Update. Afterwards event 1024 are logged to the application log stating that the installation failed with the error code 1603:
This really doesn`t help much, and in addition to the failed installation all Exchange-related services are now stopped and disabled, leaving the server offline.
Start by restoring the service-state. First, enable and start Windows Management Service using an elevated Windows PowerShell prompt:
Get-Service Winmgmt | Set-Service –StartupType Automatic; Get-Service Winmgmt | Start-Service
Then run the ServiceControl.ps1 located in the Exchange bin-folder and the pass it the argument “AfterPatch”:
The server should now be restored to an operational state. Next, download the Exchange Update Rollup if you haven`t done that in the first installation attempt. Next, retry the installation from the elevated PowerShell promt using msiexec with the /lv parameter:
msiexec /lv c:\temp\ex-ur3-install.log /update C:\temp\Exchange2010-KB981401-x64-en.msp
This will instruct the Windows Installer service to log verbose output from the installation to the file specified. After the installation fails you will see an event with event ID 1023 logged to the Application log:
Next, open the log-file and look through it for error messages. The output in this file are really verbose, so you might want to ask for assistance in the Exchange Software Updates Forum on the Exchange Server TechCenter.
In my recent troubleshooting incident I found the following in the log-file:
This indicates that the servicecontrol.ps1 script failed to run correctly. As stated in KB-article 981474 this is caused by the defined PowerShell execution polices. For the installation to succeed, oddly enough, any execution policies must be temporarily undefined.
To see if any PowerShell execution polices are defined on the system, run Get-ExecutionPolicy –List:
In this case, an ExecutionPolicy was defined both locally and in a Group Policy Object. I first cleared the Group Policy setting and then the local setting using the following command:
Execute gpupdate /force and verify that all the ExecutionPolicies are set to “Undefined”:
Redo the steps described above to restore service-state and retry the installation. In this case the installation now succeeded:
At the end I will provide some general guidelines for installing Update Rollups in Exchange Server 2007/2010:
- Use elevated Administrator-privileges when running the installation either from Windows Update or by manually downloading the installation file.
- Verify that all Execution Policies are set to “Undefined”.
- Uninstall any interim Exchange hotfixes installed since the last Update Rollup.
- Verify that the ExchangeSetupLogs directory are present on the system-drive. The installer uses this directory for saving service-state information.
Please leave a comment below if you got any further guidelines. I will update this blog-post if I gather more information regarding installing Update Rollups.
Enable and configure Windows PowerShell Remoting using Group Policy
As you may know, Windows PowerShell 2.0 introduced a new remoting feature, allowing for remote management of computers.
While this feature can be enabled manually (or scripted) with the PowerShell 2.0 cmdlet Enable-PSRemoting, I would recommend using Group Policy whenever possible. This guide will show you how this can be accomplished for Windows Vista, Windows Server 2008 and above. For Windows XP and Windows Server 2003, running Enable-PSRemoting in a PowerShell startup script would be the best approach.
Windows PowerShell 2.0 and WinRM 2.0 shipped with Windows 7 and Windows Server 2008 R2. To take advantage of Windows PowerShell Remoting, both of these are required on the downlevel operating systems Windows XP, Windows Server 2003, Windows Vista and Windows Server 2008. Both Windows PowerShell 2.0 and WinRM 2.0 are available for download here, as part of the Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0). To deploy this update to downlevel operating systems I would recommend to use WSUS, which are described in detail in this blog post by Kurt Roggen.
Group Policy Configuration
Open the Group Policy Management Console from a domain-joined Windows 7 or Windows Server 2008 R2 computer.
Create or use an existing Group Policy Object, open it, and navigate to Computer Configuration->Policies->Administrative templates->Windows Components
Here you will find the available Group Policy settings for Windows PowerShell, WinRM and Windows Remote Shell:
To enable PowerShell Remoting, the only setting we need to configure are found under “WinRM Service”, named “Allow automatic configuration of listeners”:
Enable this policy, and configure the IPv4 and IPv6 addresses to listen on. To configure WinRM to listen on all addresses, simply use *.
No other settings need to be configured, however, I`ve provided screenshots of the other settings so you can see what`s available:
There is one more thing to configure though; the Windows Firewall.
You need to create a new Inbound Rule under Computer Configuration->Policies->Windows Settings->Windows Firewall with Advanced Security->Windows Firewall with Advanced Security->Inbound Rules:
The WinRM port numbers are predefined as “Windows Remote Management”:
With WinRM 2.0, the default http listener port changed from TCP 80 to TCP 5985. The old port number are a part of the predefined scope for compatibility reasons, and may be excluded if you don`t have any legacy WinRM 1.1 listeners.
When the rule are created, you may choose to make further restrictions, i.e. to only allow the IP addresses of your management subnet, or perhaps some specific user groups:
Now that the firewall rule are configured, we are done with the minimal configuration to enable PowerShell Remoting using Group Policy.
On a computer affected by the newly configured Group Policy Object, run gpupdate and see if the settings were applied:
As you can see, the listener indicates “Source*”GPO”, meaning it was configured from a Group Policy Object.
When the GPO have been applied to all the affected computers you are ready to test the configuration.
Here is a sample usage of PowerShell Remoting combined with the Active Directory-module for Windows PowerShell:
The example are saving all computer objects in the Domain Controller Organization Unit in a variable. Then, a foreach-loop are invoking a scriptblock, returning the status of the Netlogon-service on all of the Domain Controllers.
Summary
We`ve now had a look on how to enable and configure PowerShell Remoting using Group Policy.
There are an incredible number of opportunities opening up with the new Remoting feature in Windows PowerShell 2.0. For a complete walkthrough on how you can use this new feature, I would like to recommend the excellent Administrator’s Guide to Windows PowerShell Remoting written by Dr. Tobias Weltner, Aleksandar Nikolic and Richard Giles.