OReilly Media celebrates Day Against DRM, 1/2 off Ebooks+Videos

Use code: DRM2013

Today only!

Includes my book too PowerShell for Developers
http://oreil.ly/DRM-FREE-2013

{ 0 comments }

UseAutomation

{ 2 comments }

The Python language has a translate and maketrans function that are typically used in substitution ciphers.

translate The method translate() returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string deletechars.
maketrans The method maketrans() returns a translation table that maps each character in the intab string into the character at the same position in the outtab string. Then this table is passed to the translate() function.

Using it in PowerShell

I created two PowerShell functions to mirror the Python ones Invoke-Translate  and New-TranslationTable.

The following example shows the usage of  Invoke-Translate. Here, every vowel in a string is replaced by its vowel position.

$InputTable = "aeiou"            
$OutputTable = "12345"            
$TranslationTable = New-TranslationTable $InputTable $OutputTable            
            
$string = "this is string example....wow!!!";            
            
Invoke-Translate $string $TranslationTable             
                      
th3s 3s str3ng 2x1mpl2....w4w!!!            

This example deletes all ‘x’ and ‘m’ characters from the string before doing the translate.

$InputTable = "aeiou"            
$OutputTable = "12345"            
$TranslationTable = New-TranslationTable $InputTable $OutputTable            
            
$string = "this is string example....wow!!!";            
            
Invoke-Translate $string $TranslationTable 'xm'             
            
th3s 3s str3ng 21pl2....w4w!!!

Grab the PowerShell Script

Octocat

The PowerShell script is here on GitHub.

Have fun!

{ 2 comments }

Tomasz Janczuk of Microsoft posted about owin, .NET and node.js. Here is the project on github.

The owin project allows hosting .NET 4.5 code in node.js applications running on Windows.

You need Windows x64 with node.js 0.8.x x64 installed (the module had been developed against node.js 0.8.19). You also need .NET Framework 4.5 on the machine.

PowerShell + node.js

Below is the PowerShell script at work.

The owin module allows running CPU-bound computations implemented in .NET in-process with the node.js application without blocking the node.js event loop.

image

The PowerShell script and C# implementation

The script has three steps:

  1. Compiles the C# which implements calling PowerShell as a Owinjs.Worker. This first step compiles to a DLL the C# implementing the PowerShell call simulating a CPU-bound computation. Simply, it calculates income by subtracting the cost from the revenue passed in from the JavaScript and does a Start-Sleep 5 to become CPU-bound.
  2. Next it takes the JavaScript, does a Set-Content to a file test.js.
  3. Finally, we invoke node on the test.js file created in step 2

Note: You also need the Owinjs.dll in the same directory as the script to make this happen. Download the zip file at the end of the post.

$ReferencedAssemblies = "$pwd\Owinjs.dll"            
            
$powerShell = @"

using System.Collections.Generic;
using System.Management.Automation;

namespace CalculateBudget
{
    public class Startup : Owinjs.Worker
    {
        protected override IDictionary Execute(IDictionary input)
        {
            var script = string.Format(@"{0}-{1} ; Start-Sleep 5", 
                input["revenue"], 
                input["cost"]);

            var income = PowerShell
                .Create()
                .AddScript(script)
                .Invoke()[0]
                .ToString();

            return new Dictionary { { "income", income } };
        }
    }
}
"@            
            
Add-Type -ReferencedAssemblies $ReferencedAssemblies `
    -OutputAssembly CalculateBudget.dll `
    -TypeDefinition $powerShell            
            
Write-Host -fore green "Compiled DLL"            
            
if($?) {            
            
@"
var owin = require('owin')

console.log('Starting long running operation...');
owin.worker(
    'CalculateBudget.dll',
    { revenue: 100, cost: 80 },
    function (error, result) {
        if (error) throw error;
        console.log('Result of long running operation: ', result);
    }
);

setInterval(function () {
    console.log('Node.js event loop is alive!')
}, 1000);
"@ |  Set-Content -Encoding Ascii .\test.js            
            
Write-Host -fore green "Create JavaScript file"            
Write-Host -fore green "Running nodejs"            
            
node .\test.js            
            
}

This opens interesting ways to experiment with Node, .NET and PowerShell.

Download

Here it is.       Owinjs.zip

Enjoy!

{ 2 comments }

June Blender Rogers posted on Facebook:

"2013 will be the first year in my entire life where all four digits were unique." — Jackson Cahn, born 1988.

The Question

What would a PowerShell script look like that could figure out, from a range of years, each year where all four digits are unique?

function Get-UniqueYear {            
    param(            
        $YearBorn=1987            
    )            
            
    $thisYear = (Get-Date).Year            
    [string]$targetYear = $null            
            
    foreach($targetYear in $YearBorn..$thisYear) {            
            
        $targetYearAsCharArray = $targetYear.ToCharArray()            
            
        $unique = $true            
        foreach($digit in $targetYearAsCharArray) {            
            if( ($targetYearAsCharArray -eq $digit).Count -ge 2 ) {            
                $unique = $false                            
            }            
        }            
            
        if($unique) {$targetYear}            
    }            
}

Challenge

{ 10 comments }

Jose Barreto blogged the details HERE.

His original script is fine and works.

I refactored his script this way. I prefer this style, it feels more readable. Using features of PowerShell v3 makes it easier to write scripts more concisely. Jose used PowerShell v2 techniques that still work but are more verbose and bulky.

What do you think?

Refactored Version

$CimSession = "."            

ForEach($item in Get-SmbShare -CimSession $CimSession | Where Volume) {            

    $volume = Get-Volume -CimSession $CimSession -Id $item.Volume            

    [PSCustomObject] @{            
        Share     = $item.Name            
        Path      = $item.Path            
        Size      = $volume.Size            
        Remaining = $volume.SizeRemaining             
    }            
}

Original

Get-SmbShare -CimSession FST2-FS2 |             
    ? Volume  -ne $null |             
    % {             
        $R = "" | Select Share, Path, Size, Free            
        $R.Share=$_.Name; $R.Path=$_.Path            
        Get-Volume -CimSession FST2-FS2 -Id $_.Volume |             
        % {             
            $R.Size=$_.Size; $R.Free=$_.SizeRemaining; $R | FL }            
        }

{ 4 comments }

John Cook has an interesting blog post, “Learn one Perl command”. He highlights text replacement, using the Unix command sed. But, others commented and did him one better suggesting he use a perl –pi.

PowerShell doesn’t have this out of the box. So let’s write a module.

Follow along, grab the PowerShell module here.

The PowerShell Invoke-Replace command lets you replace text:

  • In place, for any or all files in the current directory, based on a file pattern match
  • Using simple or regular expression matching
  • Plus, it can backup the target file, to the same name with an extension you supply like .bak, before editing it

The PowerShell Module

Here are Invoke-Replace and Backup-File.

function Invoke-Replace {            
    param(            
        $Match,            
        $Replace,            
        $Include="*",            
        $BackupExtension            
    )                
            
    $files = Get-ChildItem . $Include            
    ForEach($file in $files) {            
            
      Backup-File $file $BackupExtension            
      $targetFile = $file.FullName            
                  
      [IO.File]::ReadLines($targetFile) -replace $Match, $Replace |             
        Set-Content $targetFile            
    }            
}            
            
function Backup-File {            
    param(                    
        $File,            
        $BackupExtension            
    )            
            
    if(!$BackupExtension) { return }            
            
    $path = $File.FullName            
    $destination = $path + $BackupExtension            
            
    Copy-Item -Path $path -Destination $destination            
}            
            

How to Use Invoke-Replace

In the Tests subdirectory there is TestInvokeReplace.ps1 which tries out the Invoke-Replace.

For example, the following removes commas that immediately follow a digit, for all files in the current directory that have the file extension .txt.

Invoke-Replace "(?<=\d)," "" *.txt

Here’s how to do a Backup

Adding .bak as a final parameter instructs Invoke-Replace to copy the source file to the same named file and add .bak as the extension.

Invoke-Replace "(?<=\d)," "" *.txt .bak

Using Parameter Names

Here is what Invoke-Replace looks like with the parameter names specified.

Invoke-Replace -Match "(?<=\d)," -Replace "" `
    -Include *.txt -BackupExtension .bak

Learning Perl is a big commitment

Or any other scripting or programming language for that matter. What I find interesting though, is these other more established environments have been through the mine fields and collected some terrific experiences over the decades.

Transcoding their scripting experiences often yield very usable solutions.

Check out the Script

Here is the InvokeReplace module https://github.com/dfinke/PowerShellTools. I keep several others here https://github.com/dfinke including the scripts from my book “PowerShell for Developers”.

They are open source and ready to be forked and improved.

{ 0 comments }

Saturday, November 17

It is being held at the Penn State campus in Abington, PA.

I’ll be giving away copies of my book “PowerShell for Developers”.

Stop in and say hello.

{ 0 comments }

Excerpted in Dr. Dobb’s

This chapter from my book, “PowerShell for Developers”,  has been excerpted in Dr. Dobb’s.

The book also covers

Other PowerShell v3 features and more:

  • Slice and dice Text, XML, CSV, and JSON effortlessly
  • Embed PowerShell to provide scripting abilities for your C# apps
  • Create GUI applications five to ten times faster with less code
  • Leverage PowerShell’s capabilities to work with the Internet
  • Interact with DLLs and create objects, automatically display properties, and call methods in live interactive sessions
  • Build domain-specific languages (DSLs) and vocabularies to express solutions more clearly
  • Work with Microsoft Office via the Component Object Model (COM)
  • Discover PowerShell v3 features included with Windows 8 and Windows Server 2012

GitHub: Source Code and Examples From The Book

This repository contains the latest definitive bug fixed source code for the examples.

{ 0 comments }

Microsoft Scripting Guy, Ed Wilson, announced the official Honorary Scripting Guys!

What does it take to become an official Honorary Scripting Guy? It takes an extreme commitment to the scripting community, a remarkable dedication helping to spread the good word about Windows PowerShell, and a relentless pursuit of excellence in producing exceptional content.

Thank you very much Ed. It’s an honor to be selected and be a part of a great group of contributors.

{ 0 comments }

Contrat Creative Commons

© 2007-2013, Doug Finke