PowerShell: Automate Windows Azure Service Bus queue creation

One of the core services provided by the Windows Azure “cloud computing” platform is the ability to create first-in, first-out messaging queues. These queues are considered to be part of the Service Bus feature in Windows Azure. In some cases, it may be desirable to automate the creation of these queues, especially if there are a lot of them to create. By automating this process, rather than performing it manually, you can ensure consistency, repeatability, and speed.

Starting out with Windows Azure automation might lead you to download the official Microsoft Windows Azure cmdlets, or even the third-party Cerebrata Windows Azure module for Windows PowerShell. The latter module appears to have cmdlets that support queue creation, however the former (Microsoft) module does not. If you’d rather not spend the money on the Cerebrata module, can’t get your company to buy it for you, or you’d rather just stick to native Microsoft stuff, you’re still in luck. The Windows Azure .NET SDK 1.6 allows C# developers, and PowerShell script writers, to create queues using the provided .NET types!
Continue reading

PowerShell: Get the Windows Azure Certificate

If you’re automating Windows Azure using Windows PowerShell, one of the first things you’ll probably notice is that you need a management certificate to connect to the Windows Azure subscription that you’re attempting to view or modify. Management certificates are associated to a Windows Azure subscription inside the Management Portal, under the Hosted Services, Storage Accounts & CDN –> Management Certificates section (see screenshot).

Windows Azure - Management CertificatesOnce you have associated a management certificate with a subscription, it needs to be imported into your local computer’s certificate store so that it can be used from PowerShell to manage the Azure subscription. To do this, follow these directions:

  1. Open MMC
  2. Add the certificates snap-in (for current user or local computer)
  3. Navigate to the Personal –> Certificates “folder”
  4. Right-click the Certificates node and select All Tasks –> Import
  5. Select the file on the filesystem that contains the certificate
  6. Select the Personal certificate store if necessary and finish the import wizard
Next, you’ll need to grab the certificate’s thumbprint, which is basically a unique identifier that differentiates it from other certificates. To grab this, follow these steps:
  1. Double-click the certificate in the Certificates MMC snap-in
  2. Visit the Details tab
  3. Scroll down to the Thumbprint field and copy the value into Metapad or equivalent

Now that you’ve taken down the thumbprint of the certificate, you can use PowerShell to retrieve the certificate from the current user’s certificate store. If the certificate resides in the local computer’s certificate store, you’ll have to replace “CurrentUser” with “LocalMachine.” To get the certificate, check out the code below.

1
2
$AzureCertThumbprint = '4DAE6C3F444F21972B0823467C229605';
$AzureCert = Get-Item -Path cert:\CurrentUser\My\$AzureCertThumbprint;

The $AzureCert variable now holds a reference to the management certificate, and you can now use this to manage your Windows Azure subscription!

Copy Filenames to Clipboard with PowerShell

Have you ever wanted to copy a large amount of data to the Windows clipboard, but haven’t known quite how to do it? How about this scenario: you have a folder full of files, and you want to get a list of the files’ full names / paths. That’s pretty easy to do with a simple Get-ChildItem PowerShell command, but how do you then get the data into say, an e-mail, or paste it into a file? Sometimes it’s just easiest to have the data copied to the Windows clipboard for a more arbitrary usage.

This simple PowerShell script will take a folder path and copy all of the file paths to the Windows clipboard.

Important: The Windows clipboard requires that the application be running in Single-Threaded Apartment (STA) mode, so if you’re using PowerShell v2, please be sure to run PowerShell with the –STA parameter. If you use Multi-Threaded Apartment (MTA), the [Clipboard]::SetText() static method will fail.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function Copy-FileNamesToClipboard {
    # The CmdletBinding() attribute
    [CmdletBinding()]

    # Define parameters for the PowerShell v2 advanced function
    param (
        # Define a mandatory parameter called Path, which will be the path to gather files from
        [Parameter(Mandatory = $true)]
        [string] $Path
    )

    process {
        # Load the Presentation Core assembly, which contains the System.Windows.Clipboard class
        [void][Reflection.Assembly]::LoadWithPartialName("PresentationCore");

        # Initialize the text variable to an empty string
        $text = [string]::Empty;

        # Get a list of files in the specified directory
        $FileList = Get-ChildItem -Path $Path;

        # For each file in the directory, add the file path and a new line to $text
        foreach ($File in $FileList) {
            $text += ("{0}`n" -f $File.FullName);
        };

        # Set the Clipboard text to the string we just got
        [System.Windows.Clipboard]::SetText($text);
    };
};

Copy-FileNamesToClipboard -Path c:\Users\Trevor\Documents\;

PowerShell 3.0: List of Windows 8 Cmdlets & Modules

Here is a list of modules available in the new Windows Server 8:

Name
—-
ADDeploymentWF
AppLocker
Appx
BestPractices
BitsTransfer
BranchCache
CimCmdlets
ClusterAwareUpdating
DirectAccessClientComponents
Dism
DnsClient
DnsConfig
DnsLookup
DnsNrpt
FailoverClusters

 

Continue reading

AutoIT: Enumerating all Windows

Here is a short script I wrote using AutoIT, which enumerates all of the windows, to the StdOut stream:

ConsoleWrite(“Enumerating windows”)
$AllWindows = WinList()
ConsoleWrite(“Found ” & UBound($AllWindows) & ” windows”)
for $i = 0 to UBound($AllWindows) – 1
ConsoleWrite(@lf & “Name: ” & $AllWindows[$i][0])
ConsoleWrite(@lf & “HWND: ” & $AllWindows[$i][1])
next
ConsoleWrite(@lf & “Completed listing windows.”)

Note: Please ensure that you check the “console” option when compiling this script for execution. If you do not check this box, there will be no StdOut stream created, which means you will get no output.

Handy Process Management Utilities

Hey guys,

I just wanted to share a couple of cool utilities to assist with managing processes.

ImageCFG (http://www.robpol86.com/index.php/ImageCFG)

ImageCFG is a utility that lets you tweak the CPU affinity of an executable. What does this mean? Well, if you have a multi-core system, or even a hyper-threaded (virtual multi-core) system, you can restrict which cores a process can execute on. This may be desirable if there is a program that tends to hog processor time, such as a video editing application, and you want to allow it to run, but only on a restricted set of resources.

Prio (http://www.prnwatch.com/prio.html)

Although I haven’t used Prio yet, it looks to be a great, free (for personal use) program. A couple of features it offers are:

  • Save process priority settings – useful if there’s a program you always want to run in low priority / background mode
  • Always elevate certain processes – maintain good security with UAC, and convenience at the same time!
  • TCP / IP task manager tab – lets you view open network connections in real-time through task manager

——————————————

I had a need for a piece of the Prio tool, but didn’t need the entire toolset (or be able to use it freely for commercial use), so I wrote a small C# utility called “SetProcessPriority” that does just what I need it to, instead. This utility searches for a process by it’s friendly name (eg. ‘notepad‘, but without the ‘.exe’) every 2 seconds, and sets the process’ priority to “Below Normal.” This was necessary to server as a work-around to a software bug I was having with the Microsoft ConfigMgr console.

Here is the C# code for it:

using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace SetProcessPriority
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 1) return;

            string procname = args[0];
            while (1 == 1)
            {
                try
                {
                    Process[] procs = Process.GetProcessesByName(procname);
                    foreach (Process proc in procs)
                    {
                        proc.PriorityClass = ProcessPriorityClass.BelowNormal;
                    }
                }
                catch { }
                Thread.Sleep(2000);
            }
        }
    }
}

You can compile the above code in Visual Studio 2008, targeting the .NET 2.0 framework. Once you’ve compiled it into a .NET assembly, you can simply write a batch script to call it, like this:

SetProcessPriority notepad

———————————————-

Anyway, I hope this post helps someone out, out there!

Merry Christmas to all!

Failing software updates in SCCM / WSUS

I recently was troubleshooting an issue with some failing software update installations being deployed via SCCM / WSUS, and finally found out what was affecting them. All of the failed updates were related to Microsoft Office, so that kind of tells you something right there. It turns out, the root cause of the installation failure was that the “Office Source Engine” (short name ‘ose’) was disabled.

A quick, easy way to re-enable the service remotely is to use Windows PowerShell. Here is a command you can issue to set the start mode to manual:

(Get-WmiObject -Query “select * from win32_service where name = ‘ose’” -ComputerName RemoteMachine).ChangeStartMode(“Manual”)

The error messages I was getting in the UpdatesHandler.log are below:

WSUS update (32cd1fb9-5401-4025-b8dc-22a3b41060cc) installation result = 0×80070652, Reboot State = NoReboot
Update execution failed.
WSUS update (880f4592-a57e-4af6-ae6c-c2988519df4e) installation result = 0×80070652, Reboot State = NoReboot
Update execution failed.
WSUS update (8fe60694-94c6-4568-8094-17e2e92045ea) installation result = 0×80070652, Reboot State = NoReboot
Update execution failed.
WSUS update (938d8bbf-f928-4dac-baef-b66005583409) installation result = 0×80070652, Reboot State = NoReboot
Update execution failed.
WSUS update (ae97d343-7c0d-4c06-9a62-67eff01890a9) installation result = 0×80070652, Reboot State = NoReboot
Update execution failed.
WSUS update (bf20a84c-6662-4755-b60d-7fe3a090eb01) installation result = 0×80070652, Reboot State = NoReboot
Update execution failed.
WSUS update (e33db88f-49ab-4cce-aa24-16d952526b6b) installation result = 0×80070643, Reboot State = NoReboot
Update execution failed.
WSUS update (f6e3e036-eaf1-4423-9eab-9359a23fcb9e) installation result = 0×80070643, Reboot State = NoReboot
Update execution failed.
WSUS update (f75401a0-0419-48fc-8011-bb0b30c061f8) installation result = 0×80070643, Reboot State = NoReboot
Update execution failed.

Update (2009-10-29): I thought I had posted this somewhere, but I guess not. While the suggested PowerShell code above would work for a one-off fix, a better way to manage this configuration would probably be to use the Microsoft Group Policy Preferences Client Side Extensions (CSE). You can use these GPO extensions to enforce service configurations for systems with the CSE installed, thus reducing helpdesk tickets resulting from improper configurations (whether done maliciously or non-maliciously).