The PowerShell Humanizer

by Doug Finke on April 13, 2014

I started wrapping Mehdi Khalili .NET Humanizer HERE.

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities http://humanizr.net

TryPowerShellHumanizer

{ 0 comments }

How to use PowerShell to Search the Clipboard

by Doug Finke on April 9, 2014

I’m working in Visual Studio and in one of the C# applications it writes hundreds of messages to the output window. Sometimes the messages I’m looking for are strewn across the log and I need do repeated finds to get to the details I want.

So I hit on the idea to copy the text from the output window. Now, instead of pasting it to a file or in a PowerShell string, I decided to search the clipboard directly. Here’s the function and a video of it in action

function Find-OnClipboard {            
            
    param(            
        [Parameter(Mandatory=$true)]            
        $pattern            
    )            
            
    Add-Type -AssemblyName System.Windows.Forms            
                
    [System.Windows.Forms.Clipboard]::GetText() -split "`r`n" |             
        Select-String $pattern                
}            

Video

Call to Action

Add this function to your PowerShell profile, copy your favorite text to the clipboard and find info quickly and easily in any PowerShell host.

{ 0 comments }

New PowerShell Speaking Engagements

by Doug Finke on April 5, 2014

May 2014

Friday May 2, I’ll be at LOPSA-East doing a half day PowerShell training “Building your PowerShell Toolkit”. A big thanks to Steve Murawski for making this happen.

An annual conference held in NJ put on by the League of Professional System Administrators (LOPSA)

Speaking at Techorama 2014

Then from May 27-28, I’ll be at Techorama in Belgium doing two PowerShell sessions. “PowerShell for Developers” andPowerShell in a DevOps environment”.

It’s a new developer conference and the speakers they’ve lined up are great.

{ 0 comments }

Downloaded the trial Xamarin and am trying Android development in C#.

In order to get Windows 8.1 to recognize my Nexus 7 when connected via the USB, I repeated these instructions that worked for me from here.

  • Enable Developer Options
    • Settings
    • About Tablet
    • Build Number (tap 7 times to make Developer Options available in the menu)
  • Turn on Developer Options (top menu)
  • Turn USB Debugging
  • Install Google USB Driver (rev7)
  • Configure USB Computer Connection (located in the contextual menu of settings—>Storage) to appear Nexus 7 as a camera

{ 0 comments }

In Action

Here, the JavaScript is inlined as a string, the Jint Engine is created and then the JavaScript is executed.

Javascript Interpreter for .NET

You can grab jint from GitHub, or get the package from nuget.

Jint is a Javascript interpreter for .NET. Jint doesn’t compile Javascript to .NET bytecode and in this sense might be best suited for projects requiring to run relatively small scripts faster, or which need to run on different platforms. It’s available on nuget at https://www.nuget.org/packages/Jint

The PowerShell

After you get the DLL, adjust the –Path  in the Add-Type and you should be good to go.

function Invoke-JSAdd ($a, $b) {            
    Add-TypePath  "C:\jint\Jint.dll"            
            
    $JavaScript = "
        function add(a, b) { 
            return a + b; 
        }
    "            
    $add = (New-Object Jint.Engine).            
            Execute($JavaScript).            
            GetValue("add")            
            
    $add.Invoke($a, $b).ToString()            
}

The PowerShell Interop Story

This is just another great example of PowerShell’s reach/extensibility. PowerShell seamlessly integrates with .NET DLLs. The functionality in these DLLs then plug into the rest of PowerShell, and light up like a Christmas tree.

{ 0 comments }

Another Cool PowerShell Productive Tab Completion

by Doug Finke on February 16, 2014

It’s fun to find things by accident in PowerShell.

In PowerShell v3.0 (PowerShell v4.0 is the current version), new conversions were introduced. Things like an [ordered] hash table and creating a custom object from a hash table using [PSCustomObject], more HERE.

Creating a Type on the Fly

Add-Type @"
public class AddressItem
{
    public string Name  {get; set;}
    public int    Age   {get; set;}
    public string City  {get; set;}
    public string State {get; set;}
    public string Zip   {get; set;}
}
"@

This type has a default constructor and it has properties that can be set. Now you can initialize those properties from a hash table.

[AddressItem]@{            
    Name  = "John"                
    Age   = 20            
    City  = "Somewhere"            
    State = "State"            
    Zip   = "10001"            
}

Cool Tab Completion

Here is the fun new part. Once you’ve entered [AddressItem]@{ you can now type the first letter of the property and press tab to complete it.

Just another way to be more productive.

[AddressItem]@{

N<Press Tab>

}

If you want to see all the properties, here is how. I press Ctrl+Spacebar at the end of the line to get them. Unfortunately, this only seems to work when it’s on one line.

image

Note: This works for any Type not only the ones you create

{ 0 comments }

Here is how to add a times method to an integer in PowerShell to do looping.

Update-TypeData -TypeName Int -MemberType ScriptProperty `
    -MemberName Times -Force -Value {            
        1..$this            
    }

Prints

(10).Times | ForEach-Object {$_ * 2}

2 4 6 8 10 12 14 16 18 20

Or

$n=10            
$n.Times | % {$_*2}

The Update-TypeData cmdlet updates the extended type data in the session by reloading the Types.ps1xml files into memory and adding new extended type data.

{ 0 comments }

How Many PowerShell Functions Would You Make?

by Doug Finke on December 28, 2013

If you have  a GitHub login and you’ve posted Gists, this PowerShell snippet grabs the JSON, via the REST API, of the Gists you’ve uploaded . Change the $UserName, in the Invoke-RestMethod,  to another GitHub/Gist user and retrieve their Gist upload details.

If you wanted to make this reusable, how would you break up this functionality into PowerShell functions?

I know how I would. What would you do?

$UserName="UserName"            
$Password="Password"            
            
$authInfo = "{0}:{1}" -f $UserName, $Password            
$encoded  = [Text.Encoding]::UTF8.GetBytes($authInfo)            
$authInfo = [Convert]::ToBase64String($encoded)            
            
$Headers = @{            
    "Authorization" = "Basic " + $authInfo            
    "Content-Type" = "application/json"            
}            
            
Invoke-RestMethod `
    -Header $Headers `
    -Uri https://api.github.com/users/$($UserName)/gists

{ 0 comments }

PowerShell, Logic and De Morgan’s Law

by Doug Finke on December 28, 2013

My daughter will be taking a Logic next year, truth tables are fundamental. So I worked up a PowerShell example showing De Morgan’s Law.

function Get-TruthRow {            
    param($p, $q)            
            
    [PSCustomObject]@{            
        p          = $p            
        q          = $q            
        "p ^ q"    = $p -and $q            
        "p v q"    = $p -or $q            
        "~(p ^ q)" = -not ($p -and $q)            
        "~p"       = -not $p            
        "~q"       = -not $q            
        "~p v ~q"  = (-not $p) -or (-not $q)            
    }            
}            
            
"De Morgan's Law"            
$(            
    Get-TruthRow $true  $true            
    Get-TruthRow $true  $false            
    Get-TruthRow $false $true            
    Get-TruthRow $false $false            
) | Format-Table -AutoSize

The negation of a conjunction is the disjunction of the negations.

or informally as:

"not (A and B)" is the same as "(not A) or (not B)"

image

{ 0 comments }

PowerShell Can Yield Unexpected Results

by Doug Finke on December 26, 2013

PowerShell let’s you easily move from adhoc to formal. Starting at the command line, trying things out, moving the details into a file and a function, adding parameters, typing the variables and more.

PowerShell Can Guess Wrong

A simple function, you pass 123 and expect the result 6 but it returns 150.

  • So where does the coercion go wrong?
  • How many coercions happen?
  • How do we fix it?
function SumDigits([uint32]$digits) {            
                
    $s   = $digits.ToString()            
    $sum = 0            
                
    for($idx = 0; $idx -lt $s.Length; $idx += 1) {            
        $sum += $s[$idx]                            
    }            
                
    $sum            
}

What Happened

What do you think?

SumDigits 123            
            
# Prints            
150 # Expected 6

I’ll follow up in my next post.

{ 1 comment }