Monday, July 07, 2008

Microsoft Office Open Protocol Specifications

So Microsoft is releasing a lot of information on the way that it uses and support the different protocols in Office, which includes Office Communications Server 2007.

Why is this interesting for you/us? Well maybe you have a problem with ABS download, Firewall Traversal, Sending DTMF digits or similar issues that you have problems solving or maybe you are developing applications that integrate with the Microsoft UC platform; then these specifications are a excellent guide to the inner workings of OCS. Find information from the homepage here -

Microsoft Office Protocol Documents

The Microsoft Office protocol documentation provides detailed technical specifications for Microsoft proprietary protocols (including extensions to industry-standard or other published protocols) that are implemented and used by Microsoft Office 2007 to interoperate or communicate with other Microsoft products.

The documentation includes a set of companion overview and reference documents that supplement the technical specifications with conceptual background, overviews of inter-protocol relationships and interactions, and technical reference information.

Audience

The Microsoft Office protocol documentation is intended for use in conjunction with publicly available standard specifications and network programming art. It assumes that the reader either is familiar with this material or has immediate access to it.

The technical documentation provides the following levels of audience support:

  • Implementer: Sufficient conceptual and reference information for a successful implementation of one or more protocol specifications for a given task or scenario.

  • Reviewer: A definitive resource for readers who want to evaluate or understand one or more protocols.

The Microsoft Office protocol documentation provides detailed technical specifications for Microsoft proprietary protocols (including extensions to industry-standard or other published protocols) that are implemented and used by Microsoft Office 2007 to interoperate or communicate with other Microsoft products.

The documentation includes a set of companion overview and reference documents that supplement the technical specifications with conceptual background, overviews of inter-protocol relationships and interactions, and technical reference information.

Find the documentation at MSDN

Friday, July 04, 2008

Constructing commands/command line - a PowerShell hint

I was just trying to compose a correct robocopy command in my script - and instead of having robocopy to give me an error, I would like to see the command before attempting to test the command. Naturally, I could built up the command in a string and echo/execute that, but when it can be done easier (we are talking a 5 line script here) it should.

I have something like this

robocopy $from "$(split-path -parent $myinvocation.mycommand.definition)"\subpath /mir



Now, if I want to see what that resolves to, I normally would surround it with quotes, echoing it out. But when you do that, you have to take the existing quotes into account and start duplicating or escaping them. Not so great. And using single quotes is not an option as that will turn off variable substitution. Luckily, PowerShell has the here-double quote operator: @" "@. This multi-line quoting operator does not require quotes in the content to be doubled.



So to see the command, surround it with @" on the line above and place "@ on the line below. Remember that "@ must start in column 1 of the line to end the string.




@"
robocopy $from "
$(split-path -parent $myinvocation.mycommand.definition)"\subpath /mir
"
@



 



You should also remember that PowerShell has the here-single quote operator @' and '@. In this case, variable substitution is not performed.

Wednesday, July 02, 2008

Hyper-V SuperSite Article

Paul Thurrott has written/updated his Windows Server 2008 Hyper-V article. Amongst other things, it seems like Hyper-V performance is very good. Read it for yourself - worth a read!

Friday, June 27, 2008

Hyper-V RTM'ed

yesterday. So now I'll start updating my test system to see if these errors are gone:

  • Keyboard does not always work after a boot. A shutdown/start normally fixes the problem
  • Network is sometimes messed completely up if you switch the network the guest is connected to
  • "Type clipboard text" only works if you guest runs US English keyboard layout. It seems to generate/emulate keyboard stokes so slash are written as dashes (on a Danish keyboard)
  • Virtual Machine Connection crashes

Get the 64-bit update here. Remember to get rid of all save states and snapshots before upgrading! Get the full release notes here.

Tuesday, June 24, 2008

The WOW6432Node effect

Last night I was playing around with "Adding Commands to the Communicator Menus" and before I got it running I ran into an obstacle . Basically I wanted it to add extra menu entries in the Communicator menus.

The way to do this is by adding a following registry entry

HKEY_LOCAL_MACHINE\Software\Microsoft\Communicator\SessionManager\Apps\[GUID of Application]

and some keys

Name (Type:REG_SZ) to specify menu caption
ApplicationType (Type:DWORD), value can be either 0 (if application is executable) or 1 (if application is protocol)
Path (Type:REG_SZ) to specify full path to the executable
SessionType (Type: DWORD), value can be 0 (for local session), 1 (this is default for two party session) or 2 (for multi-party session)
ExtensibleMenu (Type:REG_SZ), value can be MainWindowActions, MainWindowRightClick (this is default value), ConversationWindowActions, ConversationWindowContextual (this is the default value) and ConversationWindowRightClick. Multiple values can be specified separated by semi-colons

So I started up a registry editor and added the above mentioned keys and launched my Office Communicator. But the "Contoso Sales C..." entry was missing. I did spend some time checking up on typos but came no where. So I decided to make use of Process Monitor to look for what kind of registry activities Office Communicator was having. Surprisingly the activities were only in this part of the registry HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Communicator. Just for the fun I moved my registry entry to this location and the entry in the Office Communicator worked like a charm.

The explanation for this I found on Windows IT Pro: "The Wow6432 registry entry indicates that you're running a 64-bit version of Windows. The OS uses this key to present a separate view of HKEY_LOCAL_MACHINE\SOFTWARE for 32-bit applications that run on a 64-bit version of Windows."

If you want to read more about customizing your Office Communicator the following links can useful for you.

Integrating a Third-Party Collaboration Program with Communicator 2007

Adding Commands to the Communicator Menus

How do ISA figure out which authentication to use?

So you have published your Exchange server and your are using forms based authentication (FBA). But when you use Outlook Anywhere or ActiveSync (MSRPC), it bypasses FBA. Why does it do that and how does that work?

Well, thanks to my coworker Claus-Ole Olsen, I got the question answered. ISA uses the User-Agent header/string to decide whether it will actually use FBA or not! You can also select different forms based on the value - for different device capabilities.

The ISA GUI tells you it uses FBA, but you just cannot trust that as the User-Agent header will modify the rule!

Read it all here on TechNet Microsoft Internet Security and Acceleration Server 2006 Managing User-Agent Mappings, including scripts for viewing and setting the values.

If you want to avoid the VBScript, you can use PowerShell. This is Get-IsaUserAgentMapping.ps1 -

 

param([switch]$pretty)
$root=new-object -com fpc.root
$isaArray=$root.GetContainingArray()
$mappings=$isaarray.ruleelements.UserAgentMappings |
select PersistentName,UserAgent,Description,Enabled,@{n="FBAFormsType";e={
# For values, see http://technet.microsoft.com/en-us/library/bb794715.aspx
switch ($_.FBAFormsType) { 0 {"HTML 4.01"} 1 {"cHTML"} 2 {"XHTML-MP"} 3 {"Basic"} }
}},order
if ($pretty.isPresent) {
$mappings | Sort Order | Format-Table -auto UserAgent,Description,Enabled,FBAFormsType,Order
}
else {
$mappings
}

 


Adding and modifying is left as an exercise for yourself ;)

Saturday, June 21, 2008

The first steps of programming Office Communicator

Hi there.

The last three weeks has been very exciting and the future is going to bring even greater things. You will probably ask you self why I would write this and to answer this I will use a few lines to explain.

My name is Peter and for the last few years been working in the telecommunication business. A month ago I was lucky enough to get employed by Inceptio to do consulting and development on the UC platform (E.g. OCS and Exchange).

For some time I have being reading and fooling around with the Office Communicator 2007 API SDK and it has been fun and at times frustrating. The reason for this post is to share ideas and possibilities provided by Microsoft UC platform. So to start from the beginning I thought of bringing a small and simple example and I will then continue to post more advanced samples based upon my own experiences with UC development. Below is my first example that shows how to hookup to some of the events that the Office Communicator 2007 Client exposes. Basically it writes a message in the console every time a new conversation windows starts or closes.

The example down below can be the foundation for an application that helps in retrieving information about the incoming caller. Information like calling history, email conversations, location information, billing information, project information. As one se the possibilities is endless.

In my next blog entry I will start to add functionality to retrieve some of the above mentioned information types.

Until then... 

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace EventFun
{
class EventHookUp
{
CommunicatorAPI.Messenger mCommunicator = null;
static void Main(string[] args)
{
EventHookUp hu = new EventHookUp();
hu.InitializeEventHocks();
Console.ReadKey();
}
public void InitializeEventHocks()
{
mCommunicator = new CommunicatorAPI.Messenger();
mCommunicator.OnIMWindowCreated += new CommunicatorAPI.DMessengerEvents_OnIMWindowCreatedEventHandler(mCommunicator_OnIMWindowCreated);
mCommunicator.OnIMWindowDestroyed += new CommunicatorAPI.DMessengerEvents_OnIMWindowDestroyedEventHandler(mCommunicator_OnIMWindowDestroyed);
}
void mCommunicator_OnIMWindowCreated(object pIMWindow)
{
CommunicatorAPI.IMessengerConversationWndAdvanced stpIMWindow = pIMWindow as CommunicatorAPI.IMessengerConversationWndAdvanced;
long Hwnd = (long)stpIMWindow.HWND;
Console.WriteLine("New IM Window Created : {0}", Hwnd);

//Listing Frindly name of the caller.
CommunicatorAPI.IMessengerContacts contactList = (CommunicatorAPI.IMessengerContacts)stpIMWindow.Contacts;
StringBuilder sb = new StringBuilder();
foreach (CommunicatorAPI.IMessengerContact imc in contactList)
{
sb.Append(imc.FriendlyName);
sb.Append(Environment.NewLine);
}
Console.WriteLine(sb.ToString());
}
void mCommunicator_OnIMWindowDestroyed(object pIMWindow)
{
Console.WriteLine("IM Window Destroyed.");
}
}
}



If you want to read more about the API’s then take a look at these posts/blogs



Chris Mayo -> http://blogs.msdn.com/cmayo/



Michael Dunn -> http://blogs.msdn.com/midunn/



George Durzi -> http://blogs.claritycon.com/blogs/george_durzi/default.aspx

Wednesday, June 11, 2008

Live Meeting update and GPO administrative template

Just a quick update - Microsoft has released a GPO Administrative template for Live Meeting that removes the dreaded "Test connection" dialog that end-users somehow do not fully appreciate ;-)

Find the description in KB article 948741 here and the accompanying updates for Live Meeting and the Outlook add-in that updates the clients to version 8.0.6362.70.

Original source LCSKid

Creating More Efficient Microsoft Active Directory-Enabled Applications

I just found this MSDN article about optimizing your queries. Besides good advice on how to create optimal queries, you can also instruct Active Directory to log expensive queries and even control the threshold value of when a query is expensive!

Furthermore, the ANR search is explained e.g. how you can search for 'Sam' when you do not know whether it is a name, a SAM account name etc. Just like the GUI search in Users and Computers.

 

And while you are at it, I can also recommend reading How Active Directory Searches Work.

Windows Home Server Evaluation Kit

Before getting a real kit, I would like to test it first. But so far I have not been able to find it for download anywhere. The officiel free trial page only allows you to order the kit on a DVD - not download.

Today, I found the evaluation download on connect and even better an evaluation version of Windows Home Server Power Pack 1. Power Pack seems to be Home Server'ish for  Service Pack and some new features. You can get a prerelease version of the release notes from connect.

As soon as the download finishes, I will load it up in Hyper-V :)

Thursday, June 05, 2008

winmgmt as a command line tool

The other day, I could not install AVG8 on someone's PC. Everything worked fine, but it could not register with Security Center. It turned out to be a WMI problem. I solved the problem with winmgmt and the /verifyrepository and /salvagerepository switches.

Read all the documentation about the command line switches  here at MSDN.

Thursday, May 22, 2008

Invoke-Vbscript - now supporting Vista x64

As mentioned in Is this PowerShell Session a 32-bit or a 64-bit?, Invoke-Vbscript was the reason I ventured out into that.

 

Here is the updated Invoke-Vbscript. It checks the architecture using Get-Architecture from Is this PowerShell Session a 32-bit or a 64-bit?. If it is 64-bit, it invokes the 32-bit powershell to run the script using a method described in Invoking PowerShell with complex expressions using Scriptblocks.

The script -

param($vbCode,[switch]$ExecuteStatement)

if ($args) {throw "Unknown arguments: $args"}

function PrepareVB {
$vb=new-object -com MSScriptControl.ScriptControl
$vb.language="VBScript"
$vb
}

if ((Get-Architecture -CurrentProcess) -eq 64) {
# Get path for this script
$me=$myinvocation.mycommand.path
# Build command as string to substitute values
$sb = " &'$me' -vbcode $vbcode -ExecuteStatement:`$$ExecuteStatement"
# Encode for safe command line passing
$encoded=[System.Convert]::ToBase64String([System.Text.Encoding]::UNICODE.GetBytes($sb))
# Invoke powershell 32-bit
&"$env:windir\syswow64\windowspowershell\v$($host.version.major).$($host.version.minor)\powershell.exe" -noprofile -EncodedCommand $encoded
return
}

$vb=PrepareVB
if ($ExecuteStatement.isPresent) {
$vb.ExecuteStatement($vbcode)
}
else {
$vb.Eval($vbcode)
}

Is this PowerShell Session a 32-bit or a 64-bit?

How can one identify whether the current PowerShell process is running the 32-bit version (x86) or the 64-bit version of PowerShell? Well first, why would you care? You are right, normally I do not care, but if I need to execute VBscript with Invoke-Script, I need to know as that only works on 32-bit Windows.

I'm now running Vista x64 - and that is actually a pleasure. For the first time, I feel my PC is responsive enough when running many applications. If you are interested, my PC is a Dell D830 with 4 GB RAM and a Intel Turbo Channel module having 1 GB. OK specs and nice performance.

One of the minor problems I have encountered is that MSScriptControl.ScriptControl used by Invoke-Script cannot be started from 64-bit PowerShell. I simply does not exist :(

So I set off hunting a way of finding out how to differentiate, so I could do something clever.

First, I looked at the $host variable, but that seemed to return the same info. Next, I looked at the current process. The only difference I found was the image path, there does not seem to be any flag indicating the execution mode. Strange, I would have expected that.

Before jumping on a image path test, I looked as wmi32_process as well. This did not really help me, but at least win32_operatingSystem.OSArchitecture help me figuring out the platform.

This all added up in Get-Architecture.ps1 which contains -



param([switch]$CurrentProcess)

if ($CurrentProcess.ispresent) {
$me=[diagnostics.process]::GetCurrentProcess()
if ($me.path -match '\\syswow64\\') {
32
}
else {
64
}
}
else {
$os=Get-WMIObject win32_operatingsystem
if ($os.OSArchitecture -eq "64-bit") {
64
}
else {
32
}
}


Example -



PS> powershell -noprofile {get-architecture -currentprocess}
64
PS> C:\WINDOWS\syswow64\windowspowershell\v1.0\powershell.exe -noprofile {get-architecture -currentprocess}
32
PS> powershell -noprofile {get-architecture}
64
PS> C:\WINDOWS\syswow64\windowspowershell\v1.0\powershell.exe -noprofile {get-architecture}
64
PS> powershell -noprofile {get-architecture -currentprocess}
64
PS> C:\WINDOWS\syswow64\windowspowershell\v1.0\powershell.exe -noprofile {get-architecture -currentprocess}
32


Suggestions for improvements are highly welcome!

Thursday, May 15, 2008

Interesting set of AudioCodes guides

AudioCodes has released a set of guides describing Advanced Topologies for OCS 2007 and Exchange 2007. There are several interesting scenarios including -

  • Cisco Call Manager connectivity to Office Communications Server 2007 and Exchange Server 2007
  • Single gateway for Office Communications Server 2007 and Exchange Server 2007
  • Asterisk IP-PBX connectivity to Office Communications Server 2007 and Exchange Server 2007
  • Enabling fax, modem and auxiliary devices for Office Communications Server 2007
  • PBX reduced trunk solution for Office Communications Server 2007
  • SIP trunking solution for Office Communications Server 2007

The last one about SIP Trunking looks interesting to some of my customers, it describes the following scenario -

“OCA” is a small, but growing retailer of outdoor clothing and apparel company located in New-Jersey, USA. OCA has a deployed Office Communications Server 2007 in its private network for enhanced communication within the company.
OCA decided to offer its employees Enterprise voice and to connect the company to the PSTN using a SIP trunk. OCA's major market is located in Japan and therefore, decided to select two ITSPs – TelIP located in USA and IPConnect located in Japan – for providing a SIP trunking solution. In addition, since OCA's Internet infrastructure frequently experienced interruption and loss of connection, the company decided to implement a telephony backup solution whereby in case of a connection failure with the SIP trunks, the calls are rerouted to the USA PSTN through a traditional T1 connection.

Wednesday, May 07, 2008

Using Consolas Font in your Command Window

Being a fan of using Lucida Console instead of the normal raster fonts, this is good news. You can enabled the Vista/Office 2007 Consolas font and use that. Read it all here in the IE blog.

Tuesday, May 06, 2008

New update for OC 2007 and security enhancement

My colleague Claus-Ole just pointed me to a new update on Office Communicator 2007.

This update fixes four problems and especially interesting is a fix for Terminal Server users and a enhancement to security in the High Security Policy mode, where the ABS, Custom Presence and Tabs URL's now require HTTPS. Following are the fixes -

951870 - Event IDs 8239 and 8206 are logged when you schedule and then cancel a meeting in Communicator 2007

949498 - Error message when a Communicator 2007 user sends a message that contains only Japanese characters to Communicator 2005 users: "<Username> cannot receive message in the format you used"

951871 - The presence status changes to Away for all Terminal Server users when an administrator locks the desktop or lets the screen saver run in Communicator 2007

951868 - Registry settings for certain protocols are overwritten, and Communicator 2007 becomes the default application for these protocols when you log on to Communicator 2007

Find the KB here and the download here.

Tuesday, April 29, 2008

Mac Messenger 7 available

As announced earlier Microsoft has updated the Mac Messenger client to also support Office Communications Server 2007. Following are a few snippets (Source) showing some of the OCS related functionality of the client (It still supports Windows Live)

P2P or multi-party audio/video conferencing -

Messenger Contacts

Searching the Address Book -

Messenger Contacts

Use of Mac OS X Bonjour  to detect location and ability to add personal messages

Messenger Chat

Download from here.

Thursday, April 24, 2008

Hyper-V RC0 WS08 Guest OS and multiprocessor support

When you install WS08 as a Guest OS then the WS08 media includes the earlier version of Hyper-V Integration Services, so network and other hardware devices will not work. If you launch the Integration Services CD it will tell you to go to Windows Update to upgrade the Integration Components (Catch 22 I guess).

The workaround is to 'Insert Integration Services Setup Disk' start Device Manager (devmgmt.msc) find the failing device, select 'Update Driver Software' and 'Browse my computer for driver software' - the path is then e.g. D:\support\amd64.

Second, I noticed the following limitations in multiprocessor support in Hyper-V (In the Release Notes)

For the guest operating system, install one of the following:

  • Windows Server 2008 with Hyper-V, with a maximum of 4 virtual processors. No other release of Windows Server 2008 is supported with this release of Hyper-V.
  • The Windows Server 2003 operating system, with a maximum of 1 virtual processor for 64-bit and 2 virtual processors for 32-bit.

If this is also true for the RTM version (Haven't checked yet) then this product is less useful than expected for 32 bit deployment of WS03 and practically useless for 64 bit deployments of WS03 (Even though Exchange 2007 SP1 supports Windows Server 2008, many companies won't have approval/testing for this product and/or their system management, backup etc. products ready for WS08).

Wednesday, April 16, 2008

High-Definition Video and Roundtable Hardware Requirements

Historically Microsoft published a really good whitepaper on RTAudio and QoE, but information on how the RTVideo Codec works has been sparse. But at a presentation today at Interact 2008 more details were revealed (and we where promised that more details will appear, as video gets more and more attention).

Besides all the interesting stuff about High Definition video in next versions, I just briefly wanted to touch on a few things that applies to the current versions -

P2P Video Calls with VGA quality requires Dual Core (And Quad for HD in wave 13)

So you probably know that you can change from CIF to VGA quality on P2P video calls (Not conferencing) by changing a registry key. They are documented in the release notes for OC 2007 and referenced here -

To enable VGA video in a point-to-point video call, users need to set the following registry keys on both endpoints -

[HKEY_CURRENT_USER\Software\Microsoft\RTC\Quality]
"MaxAllowedSendVideoSize"=dword:00000002
"MaxAllowedReceiveVideoSize"=dword:00000002

And restart Communicator.

But what is new to me is that the hardware requirements are actually Dual Core processors for optimal quality. It is not enforced, so VGA quality will be started with one processor, but may fall back to lower quality due to lack of CPU resoucres. In wave 13 Microsoft is talking about enforcing this requirement, so VGA will not start if you are not running from a Dual Core. In terms of HD (720P) conferencing the current requirement is going to be Quad Core processors and again the requirement will be enforced.

Roundtable quality requires Dual Core

Dual Core Processors are required for Roundtable Panorama Video but again it is not enforced, so Roundtable and Panorama Vidoe quality will be started with one processor, but may fall back to lower quality due to lack of CPU resoucres).

Thursday, April 10, 2008

Microsoft Mac Messenger update / Bloggers lunch at Interact08

Today at Interact 2008 I was invited to a Bloggers Lunch hosted by Eileen Brown. It was really good use of time and we had some interesting discussions with key Microsoft Executives including Kim Akers, UC Marketing General Manager; Eric Swift, UC Marketing Senior Director; David Lemson, Exchange Group General Manager and Amritansh Raghav, Office Communications Group, General Manager.

As part of the lunch we got what all bloggers want - news not previously announced (and that we are allowed to blog about) - so here it is ;-)

Microsoft is going to release a updated version of Mac Messenger that integrates with Office Communications Server 2007 and will include the following features -

  • Rich presence
  • Instant Messaging
  • Audio/video
  • Directory search
  • Dual sign-in with Live Messenger / OCS

So good news for all you Mac users out there. I was actually invited to participate in the beta's for this client - but my company is Mac-free area (all though I'm pretty impressed by the Vista capable MacBook Pro line of notebooks )

Friday, April 04, 2008

CU at Interact08 or MVP Summit ?

I'm leaving for Interact08 in San Diego on Monday and will be there until Sunday where I travel to MVP Summit.

At Interact08 I will (besides meetings and networking) focus my time on learning about Microsoft Online Services, Exchange Server 2007 and maybe a few OCS 2007 sessions.

At MVP Summit I guess most of my time will be spent on learning about OCS Wave 13/14 and I really look forward to this as this is my first MVP Summit.

Maybe we will meet at one of the events !? Feel free to leave a comment or contact me at e-mail/sip my.initials@inceptio.dk .

MVP Award for 2008

Some good news (for me anyway). On April first I received my MVP Award for 2008 and this (almost ;-) personal note from Mr. Ballmer himself -

clip_image001

As the independent voice of users worldwide, your influence on technical communities is felt in many ways—enhancing people’s lives and contributing to our industry’s success. We’re deeply grateful to you for sharing your feedback, comments, answers, and expertise with technical communities. In recognition of your commitment, Microsoft is pleased to honor you with the Most Valuable Professional Award. Thank you for empowering the community with your outstanding leadership!

Steven A. Ballmer
Chief Executive Officer
Microsoft Corporation

clip_image002

Thank you for your exceptional contributions to technical communities! It gives us great pleasure to present you with the Microsoft Most Valuable Professional Award for the technical expertise you generously provide to others. By sharing your knowledge, experience, and objective feedback, you inspire and help people to solve problems and discover new capabilities every day. We are honored to welcome you as a Microsoft MVP.

Rich Kaplan
Vice President, Supportability & CPE
Microsoft Corporation

Office Communicator 2007 update released

Microsoft released a new update for OC 2007 and the update fixes the following issues -

949894 - Presence functions are disabled in Communicator 2007 when you use a time zone that includes a negative partial hour on a client computer

948733 - Error message when you try to shut down a client computer that is running Office Communicator 2007: "The data file 'Mailbox - user' was not closed properly"

950492 - You cannot manually change your status from "Away" in Communicator 2007 when you use a portable computer to connect to a remote computer

948159 - Error message in Communicator 2007 if the Outlook profile file name contains non-English characters: "There was a problem connecting to Microsoft Office Outlook"

948737 - A Communicator 2007 user hears a long dial tone mixed with the streaming audio if the user takes a USB telephony device handset off the hook and then uses the device to stream audio from another application

948120 - An audio conference or a video conference fails in Communicator 2007 when you try to invite a new participant to create a multiparty conference

Find the KB/download here.

Thursday, April 03, 2008

Windows Server 2008 Exam Offer

MS has an offer where you can get a 40% discount on two exams. Register here to get the savings code.

Free Windows Server 2008 and PowerShell Scripting e-Books

Get them from here, the home of Windows Server 2008 learning, switch to the special offers tab, scroll down to Books from Microsoft Press. I cannot construct a direct link, so you have to work your way through yourself.

Tuesday, March 18, 2008

Singularity

If you are into reading hardcore stuff about compiler techniques, jit, computer architecture etc. - just a couple of times are year, this topic from Microsoft Research is for you. Microsoft Research has created a new OS callled Singularity. The purpose of it is to investigate how an OS should be built from scratch if the goal is to provide dependability and trustworthiness. An interesting paper worth a read. The RDK - Resource Devlopment Kit is found here. And you can even get the runable code from Codeplex.

After reading the research paper Singularity: Rethinking the Software Stack (only 13 pages), it came to my mind that the architecture principle of channels - e.g. a process can only communicate with other processes through well-defined channels - could be used as an interprocess communication methods and make it much easier to build high-performance distributed systems. Imagine a situation where processes can simply be put anywhere (within the limits of the required bandwidth and latency). This would enable us to use a pool of resources much more efficient and e.g. simply offload the device you are using onto other devices nearby.

Vmware Virtualization Security Best Practices

Following security Best Practices is the key to maintaining strong security
in a virtualized IT environment. Read below to get guidance on implementing and
maintaining your virtual infrastructure with Best Practices for secure design,
deployment, operations and networking


Read more here on vmware's site.

Friday, March 14, 2008

Interact08 offer and possibility to win free pass to Teched / IT Forum 2009

If wou are working with Microsoft Unified Communications then Interact08 is the place to be.

Gurdeep Singh Pall just blogged about this at the OCS Team Blog

If you see yourself as a leader in the world of unified communications, I invite you to join me and my team at INTERACT 2008 as we look at how communications have evolved and how these industry changes position you for exciting new opportunities.

INTERACT 2008 is our exclusive event focused on building community among technology professionals, specifically, those who are evaluating and deploying Microsoft’s Unified Communications products. It will be held on April 8-10 in San Diego, California and will provide ample opportunities for attendees to network with one another. More than fifty members of our product  engineering teams will be there for interactive technical sessions, birds of feather sessions, and social events at what we’re calling “PubWorld”.  I’ll be there talking about what we’re seeing in the new world of communications technology and I’d like to hear what you are seeing and hear your feedback on our products.

If you see yourself as a leader in bringing Unified Communications technologies to your organization and taking your career to the next level, I’d encourage you to come.

Register today and use this special code [OCS08].

Be among the first 5 people to register, I will buy either your ITForum 2009 or TechEd 2009 registration pass.

See you in sunny San Diego!

Gurdeep

Register today! http://www.interact08.com/ with code OCS08

New version of the OCS 2007 Planning and Supportability Guides

Just noticed that the following documents important documents where updated to version 1.2

Office Communications Server 2007 Planning Guide

Used for planning and sizing your deployments

Office Communications Server 2007 Supportability Guide

This is the ultimate guide used when you want to check if this is a "supported scenario" e.g. collocating the CWA role with a Standard Edition Server.

Wednesday, March 12, 2008

Dr. Dobb's Excellence in Programming Award 2008

This year's recipient of the Dr. Dobb's Excellence in Programming Award is
the inventor of C++, Bjarne Stroustrup

Read it all here.

Friday, March 07, 2008

Planning Tool for OCS 2007

Microsoft has RTW'ed their planning tool for OCS 2007. I have seen and tested some of the beta's and it ended up being a neat little tool.

You will input parameters such as #users, regional distribution, demand for high availability features and end up with a topology drawing looking like this -

image

and this

image

One of the good features are all the links to resources like planning steps, hardware configurations, bandwidth capacity etc.

It's a very good start, but there are still room for improvement like the ability to export the drawings in Visio format and e.g. removing the requirement for high availability at the small sites.

If you want to do more detailed capacity planning and sizing the you should definitely take a look at the OCS 2007 resource kit - it contains very good chapters on this and Excel spreadsheets for doing your own sizing.

Find the tool here.

Global Computing Platform..

A good quote from Jungle Dave -

While the media is focused on the “social” revolution changing the face of the web through sites like MySpace and Facebook, the real revolution is happening behind the scenes as the Internet changes from being a global communication platform to a global computing platform

With challengers appearing in the market JungleDisk may support multiple backing stores.

Read it all here.

Monday, March 03, 2008

OCS 2007 Software Update Services updated

Besides updates to the localized version of OCS the following issues are fixed -

  • The audit logs for the request handler are truncated when read or write operations frequently occur in Microsoft Office SharePoint Server 2007.
  • You notice a new configuration setting that is named "LogFlushSizeThreshold." This setting is added to the "Config Settings.xml" file.
  • The "thread abort Http" exception causes the upload process to stop when you try to upload the .cab files on the Communications Server 2007 Management Console.

Find the download here and the accompanying KB here.

2008 Scripting Games, Solution 10

# Advanced Event 10: Blackjack!
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent10.mspx

# -ShowValue is an aid in testing the script
param([switch]$showValues,$dealerColor=$host.ui.RawUI.ForegroundColor,$playerColor=$host.ui.RawUI.ForegroundColor)

# Define cards and their values, prepare for double-value cards (the Ace), but I did not implement the
# logic for playing with it
$cards="Hearts","Diamonds","Spades","Clubs" | % {
$suite=$_
"Ace,11,1","Two,2","Three,3","Four,4","Five,5","Six,6","Seven,7","Eight,8","Nine,9","Ten,10","Jack,10","Queen,10","King,10" | % {
$card="" | select Name,Rank,Suite,Value,Value2
$Card.Rank,$Card.Value,$Card.Value2=$_.split(",")
$card.Name=$Card.Rank + " of $suite"
$card.Suite=$suite
$card
}
}


# Shuffle (using sort-random) and place in stack - love the ability to use .net :D

[Collections.Stack] $cards=$cards | sort {(new-object random).next()}

# Show a hand
function ShowCards([switch]$dealer) {
begin {
""
if ($dealer.ispresent) {
$color=$dealerColor
write-host -foreground $color "Dealer's cards:"
}
else {
$color=$playerColor
write-host -foreground $color "Your cards:"
}
$sum=0
}
process {
if ($showValues.ispresent) {
write-host -foreground $color ("{0} ({1})" -f $_.name,$_.value)
}
else {
write-host -foreground $color $_.name
}
$sum+=$_.value
}
end {
if ($showValues.ispresent) {
write-host -foreground $color ("Total {0}" -f $sum)
}
}
}

# Stay or hit function
function Ask{
write-host -nonewline "Stay (s) or hit (h) ?"
do {
$key=$host.ui.rawui.ReadKey("noecho,includekeydown").character
} until ($key -eq "s" -or $key -eq "h")
write-host $key
$key
}

# Sum up the hand
function value{
begin {
$sum=0
}
process {
$sum+=$_.value
}
end {
$sum
}
}

$player=@()
$dealer=@()

# Start dealing
$player+=$cards.pop()
$player+=$cards.pop()
$player | ShowCards
$playervalue=$player | value

# And the dealer
$dealer+=$cards.pop()
$dealer | ShowCards -dealer
# Second card is hidden
$dealer+=$cards.pop()
$dealervalue=$dealer | value

# Player's turn

# Continue dealing until gt 21 or 'stay'
while ((ask) -eq "h") {
$player+=$cards.pop()
$player | ShowCards
$playervalue=$player | value
if ($playervalue -ge 21) {
break
}
}

"You have $playervalue"
""
$dealer | ShowCards -dealer
""

if ($playervalue -gt 21) {
"Over 21. Sorry you loose"
}
elseif ($playervalue -eq 21) {
"Black Jack. You win"
}
elseif ($dealervalue -ge $playervalue) {
"Dealer has $dealervalue. Sorry you loose"
}
else {
# Dealer playes, must continue until player is defeated, black jack or exceeds 21
while ($dealervalue -lt $playervalue) {
$dealer+=$cards.pop()
$dealer | ShowCards -dealer
$dealervalue=$dealer | value
}
if ($dealervalue -gt 21) {
"Dealer has over 21. You win"
}
elseif ($dealervalue -eq 21) {
"Dealer has Black Jack. Sorry you loose"
}
elseif ($dealervalue -ge $playervalue) {
"Dealer has $dealervalue. Sorry you loose"
}
else {
"Dealer has $dealervalue. You win"
}
}

2008 Scripting Games, Solution 9

# Advanced Event 9: You're Twisting My Words
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent9.mspx

# Load text from file
$text=type c:\scripts\alice.txt
# Split into words (space delimited)
# Convert each word to a character array, reverse the array and construct a string again
$all=$text.split(" ") | % { $w=$_.tochararray(); [array]::reverse($w); [string]::join("",$w) }
# Finally, convert all words a line of text using the default $OFS delimiter (which is space)
"$all"

2008 Scripting Games, Solution 8

# Advanced Event 8: Making Beautiful Music
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent8.mspx

param($minminutes=75,$maxminutes=80,$artistMax=2)

if ($minminutes -ge $maxminutes) {
throw "Min minutes must be smaller than max minutes"
}
# If only this file had header rows!
# Load the csv, convert each line to an object and
# convert the duration to timespans
$songs=type c:\scripts\songlist.csv | % {
$obj="" | select Artist,Song,Duration
# Multi assignment - each variable gets a value assigned
$obj.Artist,$obj.Song,$duration=$_.split(",")
$min,$sec=$duration.split(":")
$obj.Duration=new-timespan -min $min -sec $sec
$obj
}
# Randomizer
$random=new-object random

do {
$listOk=$false
write-verbose "Generating list.."
# Randomize the list
$songs=$songs | sort {$random.next()}

# Pick only $artistMax numbers per artist
$songs=$songs | group Artist | % {
$_.group[0..($random.next($artistMax))] | % { $_ }
}

# See if we can build a list
$burnSongs=@()
$burnDuration=New-Timespan
$brokeOut=$false
foreach($song in $songs) {
$burnSongs+=$song
# += does not work on timespan objects
$burnDuration=$burnDuration+$song.Duration
if ($burnDuration.totalMinutes -ge $minminutes -and `
$burnDuration.totalMinutes -le $maxminutes) {
# Is with-in constraints, exit
$listOk=$true
$brokeOut=$true
break
}
elseif ($burnDuration.TotalMinutes -gt $maxminutes) {
$brokeOut=$true
break # No need to spent more time on this list
}
}
if (!$brokeOut) {
throw "Songlist does not contain material that can fullfill the constraints"
}
} until ($listOk)
# Output duration as m:ss - the default hh:mm:ss does not seem to meet the requirements
$burnSongs | Format-Table Artist,Song,@{Label="Duration"; `
Expression={"{0}:{1:00}" -f $_.Duration.Minutes,$_.Duration.Seconds}}
# And again m:ss format
"Total music time {0}:{1}" -f [math]::truncate($burnDuration.TotalMinutes),$burnDuration.Seconds

2008 Scripting Games, Solution 7

# Advanced Event 7: Play Ball!
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent7.mspx

# Teams - as character array
$teams="ABCDEF".toChararray()
# Create combinations, use $c to start each iteration one step futher in the array
$plays=$teams | % {$c=0} { $team=$_; $c++; $teams[$c..$teams.length] | % { "$team vs. $_" } }
# Randomize - the easy way
# $plays | sort {(new-object random).next()}

# Randomize - and make sure the plan is more realistic by adding two additional
# constraints: Make sure -
# - no team plays more than 3 matches in a row and
# - a team is not left idle for 40% of a tournement
[int] $idle=[math]::truncate($plays.count*0.4)

do{
$AllTeamsOk=$true
# Randomize / shuffle deck
$plays=$plays | sort {(new-object random).next()}

# Use foreach statement as break is used
foreach($team in $teams) {
# Build a list of Y/.'s for each game a use a regex to look for consecutive matches
$teamplays=$plays | % {$g=""} { if ($_ -match $team) { $g+="Y" } else {$g+="."} } {$g}
write-debug "$team $teamplays"
if ($teamplays -match "y{3}") {
write-verbose "bad $team plays 3 matches in a row - reshuffle"
$AllTeamsOk=$false
break
}
elseif ($teamplays -match "\.{$idle}") {
write-verbose "bad $team is too much idle in the tournement - reshuffle"
$AllTeamsOk=$false
break
}
}
}
until ($AllTeamsOk)
$plays

Thursday, February 28, 2008

Controlling Diskpart from PowerShell

The other day, I got a question from one who had attended my PowerShell training classes: How do I control diskpart from a scripting language? Well, PowerShell can do it, but only because it is layered on top of .Net. And this is what I really like about PowerShell; do you do easily grow out of it.

 

The script below starts diskpart, redirects stdin/stdout and writes/reads to them. The tricky part is starting the process correctly and reading from the subprocess without stalling. The StandardOutput stream does not support timed reads, so if you read one time too many, the process freezes.

 

# ProcessStartInfo - to control stdin/stdout
$si=new-object diagnostics.processstartinfo
$si.filename="$env:windir\system32\diskpart.exe"
$si.RedirectStandardInput=$true
$si.RedirectStandardOutput=$true
$Si.UseShellExecute=$false

# Start process
$p=[diagnostics.process]::start($si)


# The difficult part - reading without stalling - and knowing when to stop
function show($maxwait=60){
# Buffer for matching the prompt
$read=""
$start=Get-Date
do {
# Touch EndOfStream to let peek see next bytes
# Do not know why, but it works
$p.StandardOutput.EndOfStream > $null
# If there is a byte pending
while ($p.StandardOutput.peek() -ne -1) {
# Get the byte as a char
$char=[char]$p.StandardOutput.read()
# Write it to the host
write-host -nonewline $char
# And save it in a buffer
$read+=$char
}
# Exit when maxwait has exceeded or the prompt at the end of the buffer
} until ($read -match "DISKPART\>\s+$" -or ((Get-Date)-$Start).TotalSeconds -gt $maxwait)
write-host
}

do {
show
$command=read-host "Command"
$p.StandardInput.Writeline($command)
} until($command -eq "exit")
# Get remaining output, no prompt at exit, so just timeout
show -maxwait 3

 


The method can also be used with other similar tools, just remember that if you do not have to keep any context, it is much easier to call the tool multiple times with different arguments. In PowerShell you can always capture the output using a simple variable -


sc $env:temp\x.x "list disk" -encoding ascii
$output=diskpart /s $env:temp\x.x

or


$ipconfig=ipconfig

 


Have fun!

2008 Scripting Games, Solution 6

# Advanced Event 6: Prime Time
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent6.mspx

# By default stop at 200
param($max=200)
2 # by definition
# Main loop, step by two as only odd numbers can be primes
for($i=3;$i -le $max; $i+=2) {
# Init prime boolean
$prime=$true
# Walk through divisors up to the number at hand
for($d=3; $d -lt $i; $d+=2) {
write-verbose "$i $d $($i % $d)"
if (!($i % $d)) {
# Divisor found, break for and look at next value
$prime=$false
break
}
}
#
if ($prime) {$i}
}

2008 Scripting Games, Solution 5

#Advanced Event 5: You Call That a Strong Password?
#http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent5.mspx

param($password)

# Start score
$score=13
# Load wordlist
$wordlist=type c:\scripts\wordlist.txt

# Tests
$len=$password.length

if ($wordlist -contains $password) {"Is a word";$score--}
if ($wordlist -contains $password.substring(0,($len-1))) {"When the last character is removed, it is a word";$score--}
if ($wordlist -contains $password.substring(1)) {"When the first character is removed, it is a word";$score--}
if ($password[0..$len] -contains "0" -and $wordlist -contains ($password -replace "0","o")) {"Is a word, where the letter 'o' is replaced with zero";$score--}
if ($password[0..$len] -contains "1" -and $wordlist -contains ($password -replace "1","l")) {"Is a word, where the letter 'l' is replaced with digit '1'";$score--}
if (!($len -ge 10 -and $len -le 20)) {"Is shorter than 10 or longer than 20";$score--}
# Find regex character classes at http://msdn2.microsoft.com/en-us/library/20bw873z.aspx
# Class d - digit
if ($password -notmatch "\d") {"Does not contain a digit";$score--}
# Class Ll - Letter, Lowercase
if ($password -cnotmatch "\p{Ll}") {"Does not contain a lowercase letter";$score--}
# Class Lu - Letter, Uppercase
if ($password -cnotmatch "\p{Lu}") {"Does not contain an uppercase letter";$score--}
# Class S - symbol, P - punctuation
if ($password -cnotmatch "\p{S}|\p{P}") {"Does not contain any symbols or punctuation";$score--}
if ($password -cmatch "\p{Ll}{4}") {"Contain more than 4 consecutive lowercase letters";$score--}
if ($password -cmatch "\p{Lu}{4}") {"Contain more than 4 consecutive uppercase letters";$score--}
if (($password[0..$len] | % {$c=0} {$c++; $password[$c..$len] -ccontains $_}) -contains $true) {
"A duplicate letter (case-insensitive) is found"
$score--
}

""
if ($score -le 6) {
"A password score of {0} indicates a weak password" -f $score
}
elseif ($score -le 10) {
"A password score of {0} indicates a moderately-strong password" -f $score
}
else {
"A password score of {0} indicates a strong password" -f $score
}

Sunday, February 24, 2008

2008 Scripting Games, Solution 4

# Advanced Event 4: Image is Everything
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent4.mspx

# Being non-native English speaking, I wanted to turn this
# into a generic calendar, that could be used anywhere
# Consequently, I created a function that by default uses
# the default culture and then specified en-US when calling
# it to comply with event rules

function Show-Calendar {
param($startDate=(Get-Date),$Culture)

if ($Culture) {
# Use supplied culture
$culture=[globalization.cultureinfo] $Culture
}
else {
# Use default culture
$culture=Get-Culture
}

# Get first day of week, the calender must be show correct
# e.g. in US Sunday is the first day of week, in Denmark Monday is the first
$firstDayOfWeek=$culture.DateTimeFormat.FirstDayofWeek
# Get the weekdays
$weekdays=$culture.DateTimeFormat.ShortestDayNames
# Calculate the width or the weekdays to right-adjust values
$width=($weekdays | measure-object -maximum length).maximum

# If first day of week is not 0, shift the order
if ([int]$FirstDayOfWeek) {
$ShiftedWeekdays=$weekdays[$FirstDayOfWeek..($WeekDays.count)] + $weekdays[0..($FirstDayOfWeek-1)]
}
else {
$ShiftedWeekdays=$weekdays
}

$StartDate=[datetime]$startDate
# Make sure we start the first day in the month
$StartDate=New-Object datetime $StartDate.year,$StartDate.month,1

# Working date
$Date=$StartDate

# Header
$Date.ToString($culture.DateTimeFormat.YearMonthPattern,$culture)

# Process scriptblock and pipe output to Format-Table
&{
while ($date.Month -eq $StartDate.Month) {
# Week-break code
if ([int]$date.DayOfWeek -eq $firstDayOfWeek -and $week) {
$week
$week=$null
}
# Create week object with days as properties
if (!$week) {
$week=New-Object Object
$ShiftedWeekdays | % {
Add-Member -inputObject $week NoteProperty $_ $null
}
}
# Get the day e.g. the property name
$dayOfWeek=$Weekdays[$date.DayOfWeek]
# Assign value to property
$week.$dayOfWeek="{0,$width}" -f $date.day # Right adjust values
# Values must be right-aligned as the days will $null-values will
# set off Format-Table left-aligning those columns

# Next day
$date=$date.AddDays(1)
}
if ($week) {
# Print out final week, if any
$week
}
} | Format-Table -autosize # Pick up the alias properties and format it

}

# Prompt user
$month=read-host "Enter month in month/year format"
# Split into month and year
$month,$year=$month.split("/")
# And call function with en-us culture
Show-Calendar (New-Object Datetime $year,$month,1) "en-us"

2008 Scripting Games, Solution 3

# Advanced Event 3: Instant (Runoff) Winner
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent3.mspx

# Load all votes from the file
$allvotes=type c:\scripts\votes.txt

# While-true in lack of a real do-loop construct
while ($true) {
# Pick up the first name from each line
$votes=$allvotes | ? {$_} | % {$vote,$null=$_.split(","); $vote }
# Save the count
$count=$votes.count
write-verbose "count=$count"
# Use Group combined with select and a calculated property to get percentages
$result=$votes | Group | Select Name,@{Name="Percentage";Expression={$_.count / $count * 100}}
# Do we have a winner? If a percentage is larger than 50, we do
if (($result | measure-object -Maximum Percentage).Maximum -gt 50) {
# Get winner, only one can be returned
$winner=$result | ? {$_.Percentage -gt 50}
# Format output as requested
"The winner is $($winner.name) with $($winner.percentage.tostring('##.#'))% of the vote."
# Exit while
break
}
write-verbose "Winner not found"
# Find candidate that needs to be eliminated
$fewestVotes=$result | sort Percentage | Select -First 1
write-verbose "Fewest votes $fewestVotes"
# Modify votes by removing candidate with fewest votes
# Each line is turned into an array, the array is converted back into
# a comma-separated line excluding the candidate
# Note how -ne can be used to remove values from a collection/array
$allvotes=$allvotes | % {
$votes=$_.split(",")
[string]::join(",",$votes -ne $fewestVotes.Name)
}
}

Wednesday, February 20, 2008

2008 Scripting Games, Solution 2

# Advanced Event 2: Skating on Thin Ice
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent2.mspx

# Construct a hash table for skater,score combinations
$skaters=@{}
type c:\scripts\skaters.txt | % {
# Split line into name and an array of results
$name,$results=$_.split(",")
# Calculate the sum, max and min
$measure=$results | measure-object -sum -max -min
# Get the result that counts by excluding max and min scores
$result=$measure.sum - $measure.maximum - $measure.minimum
# Calc the average score
$score=$result / ($results.count-2)
# Save in assoc array
$skaters.$name=$score
}
# Get the 3 highest values, GetEnumerator must be used to get name-value properties
$skaters.GetEnumerator() | sort -desc value | Select -first 3 | % {
# Metal values
$metal="Gold","Silver","Bronze"
# Index into metal
$c=-1
} {
# Increament metal index
$c++
# Write-out winner
"{0} medal: {1}, {2}" -f $metal[$c],$_.name,$_.value
}

2008 Scripting Games, Solution 1

Here's my solution -

# Advanced Event 1: Could I Get Your Phone Number?
# http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent1.mspx

$number=read-host "Enter phone number"
# Combine a pipeline with the foreach statement
# This is necessary as only the first match is needed and break is then used
# to abort the loop
# The pipeline picks words 7 characters long
foreach($word in type c:\scripts\wordlist.txt | ? { $_.length -eq 7 }) {
# Convert letters to numbers
if (($word -replace "[abc]","2" -replace "[def]","3" -replace "[ghi]","4" `
-replace "[jkl]","5" -replace "[mno]","6" -replace "[prs]","7" `
-replace "[tuv]","8" -replace "[wxy]","9") -eq $number ) {
# Emit result in uppercase
$word.toupper()
# Exit foreach loop
break
}
}

Tuesday, February 19, 2008

Using Live ID (a.k.a Passport) on your own site - for free!

Suddenly, it seems like you can do that now. I checked it out when Passport first came out and at that time you had to pay a lot to use the service. Now it seems to be free! I wonder whether you can integrate it directly into IISv6 - could be nice for customer access to our site and I could also see it used in combination with hosted Sharepoint (that I'm running for a small club - no more messing with passwords and email).

Benefits of Web Authentication

The benefits of incorporating Windows Live ID into your Web site include:

  • The ability to use Windows Live gadgets and controls to incorporate authenticated Windows Live services and data into your site.
  • An HTTP-based, platform-neutral interface for implementing Windows Live ID authentication in your existing site, even if it is hosted by a third-party.
  • Freedom from the technical details of authentication! The Windows Live ID authentication service handles this for you.
  • A huge user base: any of the millions of users who have a Windows Live ID can become a user of your site.

Read more in the SDK and get it here.

As soon as Live Id starts to support CardSpace (formerly Infocards) (seems like it is in progress), things are both easy for as well the administrator as the user.

Want to Crash PowerShell?

Try -

$x=1; $x.$y=1

 


It seems like any indirect property reference, when the referencing variable is $null, will crash PowerShell. Consequently, you can do it on any built-in variable like this -


$input.$null=1

 


I will report it to Microsoft. I do not know whether it has been reported or not as my connect.microsoft.com connection to PowerShell does not work :(

Monday, February 18, 2008

2008 (Winter) Scripting Games

Microsoft Script Center has started their yearly Scripting Games February 15 - March 3, 2008.

2008 Winter Scripting Games

If you are new to scripting, need a brush-up or are breathing scripts, I encourage you to join.

I will attended the Advanced Division in PowerShell myself. Why do it in VBScript, when you can do it much easier with PowerShell? ;) And Perl I do not know.

I'm planning to publish my solutions as the deadlines have passed.

Have fun

Thursday, February 14, 2008

Get Active Directory object GUID one-liner

[guid]((([directoryservices.directorysearcher] "(samaccountname=theuser)").findall())[0].properties.getenumerator() | ? { $_.name -eq "objectguid"}).value[0]




Comments -




  • Construct a DirectorySearcher with an LDAP search filter


  • Surround expression with parenthesis to use the returned value (this technique is used multiple times)


  • Find all objects


  • Take the first (and only) by indexing with [0]


  • Get the properties


  • Convert to an enumerator, so they are available in name-value pairs


  • Filter out anything but objectGuid using Where-Object (?)


  • Get the first value, as the value is always a collection


  • Convert the value - it is a byte[] to a guid, by type-casting it with [guid]