23 Feb 2012

I was called out on my approach on this in work today, so I thought I would share my thoughts on this topic. The actual executable concerned was STSADM command line tool for SharePoint 2010 (yes, STSADM is still useful in SharePoint 2010, for example in enabling self-service site creation). Unfortunately, I don’t have STSADM installed on the machine I’m writing this blog post on, so I use the example of calling Internet Explorer instead. The principal is the same in both cases.

But if you try and run the above command in PowerShell, you will get the following error:

To correct the error, we need to enclose the path to the iexplore.exe file in quotes:

“C:\Program Files\Internet Explorer\iexplore.exe”

But this will not actually result in IE being called; this is because PowerShell treats the input as a string, and will simply write the text enclosed in the quotes to the console. To run the string as a script whose path is enclosed in quotes, you preface the string with the call operator (ampersand):

And this PowerShell statement will call Internet Explorer so that it opens at the BBC News site in p0rnInPrivate mode. So that we can see that to call STSADM from PowerShell, we could use the following command:

And this would work. Except, of course, that no self respecting software developer would leave should a horribly long line of code in a script. They would refactor this line of code by using an alias for the STSADM executable, and so avoid having to repeatedly use a hard-coded literal for the executable path. They would also realise that the location of the common programs varies according to how Windows itself was installed on the target computer, and make use of the %CommonProgramFiles% environment variable:

1 comment:

To my shame I didn't actually realise that PowerShell existed until your posts. Still, new lesson learned. As you know I'm more of a Linux user these days but I'll definitely give it a look. Cheers for the tip.