PowerShell v3 Script

$url = "http://goo.gl/aU1pB"            

$r = ((Invoke-WebRequest $url).AllElements |
    Where class -eq 'column-count column-count-3' |
    Select -First 1).innerText -Split "`r`n" |
    ForEach {[PSCustomObject]@{Name=$_}}            

$r | Format-Wide -Column 3
"Total {0}" -f $r.Count

Organizations that support the Stop Online Piracy Act include:

Currently, 128. Wikipedia keeps the list updated.

60 Plus Association                                     ABC                                                     Alliance for Safe Online Pharmacies (ASOP)
American Bankers Association (ABA)                      American Federation of Musicians (AFM)                  American Federation of Television and Radio Artists ...
American Society of Composers, Authors and Publisher... Americans for Tax Reform                                Artists and Allied Crafts of the United States
Association of American Publishers (AAP)                Association of State Criminal Investigative Agencies    Association of Talent Agents (ATA)
Beachbody, LLC                                          BMI                                                     BMG Chrysalis
Building and Construction Trades Department             Capitol Records Nashville                               CBS
Cengage Learning                                        Christian Music Trade Association                       Church Music Publishers’ Association
Coalition Against Online Video Piracy (CAOVP)           Comcast/NBCUniversal                                    Concerned Women for America (CWA)
Congressional Fire Services Institute                   Copyhype                                                Copyright Alliance
Coty, Inc.                                              Council of Better Business Bureaus (CBBB)               Council of State Governments
Country Music Association                               Country Music Television                                Creative America
Deluxe Digital Studios                                  Directors Guild of America (DGA)                        Disney Publishing Worldwide, Inc.
Elsevier                                                EMI Christian Music Group                               EMI Music Publishing
Entertainment Software Association (ESA)                ESPN                                                    Estée Lauder Companies
Foundation for Job Creation ( www.jobcreation.us)       Fraternal Order of Police (FOP)                         Gospel Music Association
Graphic Artists Guild                                   Hachette Book Group                                     HarperCollins Publishers Worldwide, Inc.
Hyperion Books                                          Independent Film & Television Alliance (IFTA)           Information Technology and Innovation Foundation (IT...
International Alliance of Theatrical and Stage Emplo... International AntiCounterfeiting Coalition (IACC)       International Brotherhood of Electrical Workers (IBEW)
International Brotherhood of Teamsters (IBT)            International Trademark Association (INTA)              International Union of Police Associations
L’Oreal                                                 Lost Highway Records                                    Macmillan
Major County Sheriffs                                   Major League Baseball                                   Majority City Chiefs
Marvel Entertainment, LLC                               MasterCard Worldwide                                    MCA Records
McGraw-Hill Education                                   Mercury Nashville                                       Minor League Baseball (MiLB)
Minority Media & Telecom Council (MMTC)                 Motion Picture Association of America (MPAA) [5]        Moving Picture Technicians
MPA – The Association of Magazine Media                 National Association of Manufacturers (NAM)             National Association of Prosecutor Coordinators
National Association of State Chief Information Offi... National Cable & Telecommunications Association (NCTA)  National Center for Victims of Crime
National Criminal Justice Association                   National District Attorneys Association                 National Domestic Preparedness Coalition
National Football League                                National Governors Association, Economic Development... National League of Cities
National Narcotics Officers’ Associations’ Coalition    National Sheriffs' Association (NSA)                    National Songwriters Association
National Troopers Coalition                             News Corporation                                        Nike, Inc.
Pearson Education                                       Penguin Group (USA), Inc.                               Pharmaceutical Research and Manufacturers of America...
Pfizer, Inc.                                            Provident Music Group                                   Random House
Raulet Property Partners                                Republic Nashville                                      Revlon
Scholastic, Inc.                                        Screen Actors Guild (SAG)                               Showdog Universal Music
Sony/ATV Music Publishing                               Sony Music Entertainment                                Sony Music Nashville
State International Development Organization (SIDO)     The National Association of Theatre Owners (NATO)       Perseus Books Group
United States Conference of Mayors                      Tiffany & Co.                                           Time Warner
True Religion Brand Jeans                               UMG Publishing Group Nashville                          United States Chamber of Commerce
United States Olympic Committee                         United States Tennis Association                        Universal Music
Universal Music Publishing Group                        Viacom                                                  Visa Inc.
W.W. Norton & Company                                   Wallace Bajjali Development Partners, L.P.              Warner Music Group
Warner Music Nashville                                  Wolters Kluwer Health                                   Word Entertainment
World Wrestling Entertainment (WWE)                     Zumba Fitness, LLC
Share

{ 3 comments }

Find the sum of all the multiples of 3 or 5 below 1000

What do you think?

  • Version 1 captures the essence better, less ceremony than Version 2
  • Version 2 is faster PowerShell – Four For Loops and their timings
  • Version 2 is a more recognizable way of coding
  • Version 1 requires more work to understand if you’re not used to it

Version 1

0..999 |
    Where   {$_ % 3 -eq 0 -Or $_ % 5 -eq 0 } |
    ForEach {$total=0} {$total+=$_} {$total}            

Version 2

$total=0
for($i=0; $i -lt 1000; $i+=1) {
    if($i % 3 -eq 0 -Or $i % 5 -eq 0) {
        $total+=$i
    }
}
$total
Share

{ 8 comments }

How would you solve it?

This Call to C#

Add-Type -Language CSharpVersion3 -TypeDefinition @"
using System;
using System.Collections.Generic;
using System.Linq;

public class TestClass {
    public void Test(IEnumerable<int> id) {
        id.ToList().ForEach(i=> Console.WriteLine("{0}\r", i));
    }
}
"@            

(New-Object TestClass).Test((1,2,3))            

Results in this Error

Cannot convert argument "id", with value: "System.Object[]", for "Test" to type
    "System.Collections.Generic.IEnumerable`1[System.Int32]": "Cannot
convert the "System.Object[]" value of type "System.Object[]" to type
    "System.Collections.Generic.IEnumerable`1[System.Int32]"."
At C:\testClass1.ps1:12 char:1
+ (New-Object TestClass).Test((1,2,3))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

One Solution

In PowerShell, I can code around it by explicitly typing  the array. I don’t like it, too much typing.

(New-Object TestClass).Test([int[]](1,2,3))

Thoughts

Since I have access to the C# source, I’d prefer to use int[] id and not use IEnumerable for the parameter in the Test method.  This way, when others work with my code from PowerShell the principal of least surprise is at work. How much do I trade doing it this way? Is it only style points?

How would you solve it?

Share

{ 3 comments }

Check out the Microsoft Channel 9 video Node.js Windows Azure Introduction, it’s a nice quick intro and shows the PowerShell cmdlets in action and an intro node.js application. The PowerShell cmdlets have help and examples. Plus, they let you interact with the Azure emulator letting you test your node.js app before deploying to the cloud.

I downloaded the pieces from Windows Azure SDK for Node.js.

Here is how you can load up Azure PowerShell for node.js. It’s great, if you are used to working with PowerShell, the Azure PowerShell cmdlets play right into the ecosystem.

Import-Module 'C:\Program Files\Microsoft SDKs\Windows Azure\Nodejs\Nov2011\PowerShell\AzureDeploymentCmdlets.dll'
(Get-Module AzureDeploymentCmdlets).ExportedCommands.Keys | sort            

# Prints
Add-AzureNodeWebRole
Add-AzureNodeWorkerRole
Get-AzurePublishSettings
Get-AzureStorageAccounts
Import-AzurePublishSettings
New-AzureService
Publish-AzureService
Remove-AzureService
Set-AzureDeploymentLocation
Set-AzureDeploymentSlot
Set-AzureDeploymentStorage
Set-AzureDeploymentSubscription
Set-AzureInstances
Start-AzureEmulator
Start-AzureService
Stop-AzureEmulator
Stop-AzureService
Share

{ 1 comment }

 

 

I am reading and reviewing NumPy 1.5 Beginner’s Guide. I like the examples the author presents and I figured I’d reproduce some using PowerShell.

 

 

PowerShell Code

Here is one: From a date range, display the second to last Friday.

I foreach over a range of numbers, starting with an initial date (in the Begin Block of the ForEach), adding a day each time through the loop (in the Process Block of the ForEach), picking out only the Friday dates with the Where cmdlet. This returns an array of dates, so I use array slicing to display the second to last element using [-2].

(1..31 |
    ForEach {$date = Get-Date("11/30/11")} {
        $date = $date.AddDays(1)
        $date
    } | Where {$_.DayOfWeek -eq "Friday"})[-2]            

# Prints
Friday, December 23, 2011 12:00:00 AM
Share

{ 3 comments }

Mark Watson posted, Using the New York Times Semantic Web APIs. In it, he uses Clojure , AllegroGraph 4, Star Dog RDF repositories and his own NLP code.

After requesting API Key from the New York Times, I worked up this reusable query in PowerShell. Time for more exploration.

Note: This PowerShell code only works on Version 3. I am using the new cmdlet Invoke-RestMethod and the simplified Where syntax.

Get-SemanticNYT "obama" |
    Get-SemanticNYTArticles |
    where links |
        select -ExpandProperty article_list |
        select -ExpandProperty results |
        select Title, Date, Body | Out-GridView

Injecting a GUI into the Command Line

Out-GridView is one of the cmdlets delivered with PowerShell.

image

PowerShell Code

PowerShell’s parameter binding saves time and effort. Specifying ValueFromPipelineByPropertyName, lets me quickly pipe results from one Web API to the other. Letting PowerShell do the work of binding the output from one function to the other. This lets me focus on problem solving.

Invoke-RestMethod does all the heavy lifting when interacting with the Web, (Invoke-RestMethod $uri).results:

  • Hits the endpoint
  • Retrieves the JSON
  • Converts the JSON to PowerShell objects 
function Get-SemanticNYT {            

    param($query = "obama")            

    $uri = "http://api.nytimes.com/svc/semantic/v2/"+
        "concept/search.json?query=$query&api-key=$apiKey"            

    (Invoke-RestMethod $uri).results
}            

function Get-SemanticNYTArticles {            

    param(
        [Parameter(ValueFromPipelineByPropertyName)]
        $concept_name,
        [Parameter(ValueFromPipelineByPropertyName)]
        $concept_type
    )            

    process {
      $uri = "http://api.nytimes.com/svc/semantic/v2/" +
      "concept/name/$concept_type/$concept_name.json?&" +
      "fields=all&api-key=$apiKey"            

      (Invoke-RestMethod $uri).results
    }
}
Share

{ 3 comments }

PowerShell V3 CTP 2 was released, HERE. There is more polish to the product.

Digging around ISE (Integrated Scripting Environment), the $psISE variable has several properties that let you interact with ISE environment. I found the ToggleOutliningExpansion method and added it to the Add-on menu with a shortcut key, all accessible through the $psISE variable.

These are all examples of how PowerShell helps me optimize my time and effort.

Note: As Ravi points out in the comments. This feature is already hooked up to Ctrl-M under the Edit menu.

Toggle All Regions Add-on

$DisplayName = "Toggle All Regions"
$Action      = {$psISE.CurrentFile.Editor.ToggleOutliningExpansion()}
$ShortCut    = "CTRL+ALT+L"            

$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add($DisplayName, $Action, $ShortCut)

image

Before

image

Press Ctrl+Alt+L

And all of the regions are collapsed.

image

Now, Expand What You Need

Or, press Ctrl+Alt+L to expand all regions.

image

Share

{ 2 comments }

Update

Great feedback from the PowerShell community. I now use [Math]::Floor to avoid an error in rounding, if I use [int] it rounds up. Plus I de-pluralized the names of the functions. Thanks Chris and Aleksandar.

This script lets you see your Twitter followers name, screen name and location. Using the new Invoke-RestMethod in PowerShell Version 3, it retrieves and converts the JSON to make it easily accessible in PowerShell.

Get-TwitterFollower dfinke | Out-GridView

image

The Code

function Get-TwitterFollower ($screenName) {                        

    $baseUrl = "https://api.twitter.com/1"
    function Get-Follower ($userIds) {
        $userIds = @($userIds) -join ","
        $url = "$baseUrl/users/lookup.json?user_id=$($userIds)&include_entities=true"
        (Invoke-RestMethod $url) |
            select  name, screen_name, location
    }                                    

    $url = "$baseUrl/followers/ids.json?cursor=-1&screen_name=$($screenName)"
    $followers = (Invoke-RestMethod $url).ids                                     

    $blocks   = [Math]::Floor($followers.Count / 100)
    $leftover = $followers.Count % 100                                    

    for($idx=0; $idx -lt $blocks; $idx+=1) {
        Get-Follower ($followers | select -First 100 -skip ($idx*100))
    }            

    Get-Follower ($followers | select -First $leftOver -skip ($idx*100))
}
Share

{ 7 comments }

I’ve been invited to review the new NumPy book.

NumPy (from Numerical Python) is an open source Python library for scientific
computing. NumPy lets you work with arrays and matrices in a natural way.

I blogged about NumPy and SciPy for IronPython / #.Net. These libraries have be been optimized and provided custom .Net interfaces. This means that the full functionality is available to all .Net languages.

That means PowerShell, so I’m interested.

NumPy contains a long list of useful mathematical functions including some for linear algebra,
Fourier transformation, and random number generation routines. NumPy allows rapid interactive prototyping.

Here is a sample chapter from the book. Python has been around since the early 90’s and their open source libraries are very mature and can shortcut plenty of work.  That coupled with IronPython for .Net means a potentially seamless integration with PowerShell. NymPy is used by scientists, engineers, quantitative data analysts and more.

I am looking forward to learning more about how to use it and where it is applied.

Share

{ 3 comments }

I was Googling for the Strategy Pattern and implementations done in dynamic languages and came across Neal Ford’s slides where he implements it in Groovy. Here are Peter Norvig’s slides, Design Patterns in Dynamic Languages, in it he states that 16 of the 23 GoF patterns have qualitatively simpler implementations in dynamic languages. Mr. Norvig is Director of Research at Google.

One of Neal Ford’s slides captures the idea.

image

The Strategy Pattern

Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

function ql {$args}            

function CalcByMult {
    param($n,$m)             

    $n*$m
}            

function CalcByManyAdds {
    param($n,$m)            

    1..$n | % {$result = 0} { $result += $m } {$result}
}            

$sampleData = @(
    ,(3,4,12)
    ,(5,-5,-25)
)            

$strategies = ql CalcByMult CalcByManyAdds            

foreach($Dataset in $sampleData) {
    foreach($strategy in $strategies) {
        $Dataset[2] -eq (& $strategy $Dataset[0] $Dataset[1])
    }
}

Why Bother with Extra Structure?

Here I am creating an array of PowerShell script blocks for the strategies, eliminating the ceremony of naming them.

$sampleData = @(
    ,(3,4,12)
    ,(5,-5,-25)
)            

$strategies =
{param($n,$m) $n*$m},
{
    param($n,$m)
    1..$n | % {$result = 0} { $result += $m } {$result}
}            

foreach($Dataset in $sampleData) {
    foreach($strategy in $strategies) {
        $Dataset[2] -eq (& $strategy $Dataset[0] $Dataset[1])
    }
}
Share

{ 4 comments }

Contrat Creative Commons

© 2007-2012, Doug Finke