Cleanup WSUS – Remove Computers No Longer in the Domain

One thing I love about WSUS is the ability to monitor the presence of clients. It gives me a good approximation of the last time a computer was on the network. I often use this information to help me clean missing computers out of Active Directory.

But what about when a computer is removed from the domain before it is removed from WSUS? Rather than manually checking, I wrote an IronPython script that compares the list of computers in Active Directory with the computers on WSUS. When I run this script, it lists computers that should be removed from WSUS, and deletes them for me (after prompting).

Continue reading Cleanup WSUS – Remove Computers No Longer in the Domain

Embedding IronPython

In my current programming project, I’ve embedded IronPython in a C# program. I thought I would share the basics of embedding a scripting engine. I imagine the process would be the same for any language that uses the DLR (Dynamic Language Runtime), like IronRuby. Here is a sample using IronPython 2.0 Beta 5.

using System;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

public class Program
{
    // Delegate matching the signature of the factorial function
    delegate int FactorialDelegate(int n);

    static void Main(string[] args)
    {
        // Our factorial function
        string[] lines = {"def factorial(n):",
                          "  for i in range(1, n):",
                          "    n = n * i",
                          "  return n"};

        string code = String.Join("\r", lines);

        // Instantiate the IronPython environment
        ScriptEngine engine = Python.CreateEngine();

        // Create a scope/module to work in
        ScriptScope scope = engine.CreateScope();

        // A little preparation
        ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);

        // Compile the code
        CompiledCode compiled = source.Compile();

        // Execute the code in the scope
        compiled.Execute(scope);

        //Now the factorial function exists in the IronPython environment. Let's use it.

        // Set x = 5
        scope.SetVariable("x", 5);

        // print factorial(x)
        ScriptSource print = engine.CreateScriptSourceFromString("print factorial(x)", SourceCodeKind.SingleStatement);
        print.Execute(scope);       //outputs 120

        // Get the result from IronPython
        int result1 = scope.Execute<int>("factorial(6)");
        Console.WriteLine(result1); //outputs 720

        // We can also call the function directly from C#
        FactorialDelegate factorial = scope.GetVariable<FactorialDelegate>("factorial");
        int result2 = factorial(7);
        Console.WriteLine(result2); //outputs 5040

        Console.Read();
    }
}