shell page 2 - Dave's Blog

Search
My timeline on Mastodon

clip.exe - Useful tool I didn't know shipped with Windows

2011 May 26, 11:00

When you run clip.exe, whatever comes into its standard input is put onto the clipboard. So when you need to move the result of something in your command window somewhere else you can pipe the result into clip.exe. Then you won't have to worry about the irritating way cmd.exe does block copy/pasting and you avoid having to manually fixup line breaks in wrapped lines. For instance, you can put the contents of a script into the clipboard with:

more cdo.cmd | clip

I've got a lot of stuff dumped in my bin folder that I sync across all my PCs so I didn't realize that clip.exe is a part of standard Windows installs.

Nice for avoiding the block copy in cmd.exe but I'd prefer to have the contents sort of tee'd into the clipboard and standard output. So TeeClip.ps1:

$input | tee -var teeclipout | clip;
$teeclipout;
PermalinkCommentspowershell clip tool clipboard cli technical windows tee

PowerShell Script Batch File Wrapper

2011 May 22, 7:20

I'm trying to learn and use PowerShell more, but plenty of other folks I know don't use PowerShell. To allow them to use my scripts I use the following cmd.exe batch file to make it easy to call PowerShell scripts. To use, just name the batch file name the same as the corresponding PowerShell script filename and put it in the same directory.

@echo off
if "%1"=="/?" goto help
if "%1"=="/h" goto help
if "%1"=="-?" goto help
if "%1"=="-h" goto help

%systemroot%\system32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -Command . %~dpn0.ps1 %*
goto end

:help
%systemroot%\system32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -Command help %~dpn0.ps1 -full
goto end

:end

Additionally for PowerShell scripts that modify the current working directory I use the following batch file:

@echo off
if "%1"=="/?" goto help
if "%1"=="/h" goto help
if "%1"=="-?" goto help
if "%1"=="-h" goto help

%systemroot%\system32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -Command . %~dpn0.ps1 %*;(pwd).Path 1> %temp%\%~n0.tmp 2> nul
set /p newdir=
PermalinkCommentspowershell technical programming batch file console

Powershell to test your XPath

2011 Apr 14, 5:11This page and esp. the final comment on the page were very helpful with describing how to parse XML in PowerShell.PermalinkCommentspowershell xml xpath technical programming

Chapter 16. The Registry - Master-PowerShell | With Dr. Tobias Weltner - Powershell.com – Powershell Scripts, Tips and Resources

2011 Jan 4, 7:25How to take ownership and re-ACL registry keys from a powershell prompt.PermalinkCommentstechnical powershell acl regkey registry windows

Windows 7 Accelerator Platform COM / C# Interop

2010 Aug 20, 11:20

For a new project I'm working on involving IE's installed Accelerators and OpenSearch search providers via the Windows 7 Accelerator Platform, I've created a C#/COM interop class for those APIs.

Download the osinterop.cs interop file here.

PermalinkCommentstechnical accelerator csharp com

DVD Ripping and Viewing in Windows Media Center

2010 Aug 17, 3:05

I've just got a new media center PC connected directly to my television with lots of HD space and so I'm ripping a bunch of my DVDs to the PC so I don't have to fuss with the physical media. I'm ripping with DVD Rip, viewing the results in Windows 7's Windows Media Center after turning on the WMC DVD Library, and using a powershell script I wrote to copy over cover art and metadata.

My powershell script follows. To use it you must do the following:

  1. Run Windows Media Center with the DVD in the drive and view the disc's metadata info.
  2. Rip each DVD to its own subdirectory of a common directory.
  3. The name of the subdirectory to which the DVD is ripped must have the same name as the DVD name in the metadata. An exception to this are characters that aren't allowed in Windows paths (e.g. <, >, ?, *, etc)
  4. Run the script and pass the path to the common directory containing the DVD rips as the first parameter.
Running WMC and viewing the DVD's metadata forces WMC to copy the metadata off the Internet and cache it locally. After playing with Fiddler and reading this blog post on WMC metadata I made the following script that copies metadata and cover art from the WMC cache to the corresponding DVD rip directory.

Download copydvdinfo.ps1

PermalinkCommentspowershell wmc technical tv dvd windows-media-center

TiMER

2010 Jun 29, 1:24

An excellent movie I'd never heard of. An entertaining and humorous sci-fi indie romance comedy. It stars Emma Caulfield (who I recognize as Anya from Buffy the Vampire Slayer) who obsesses over her timer, an implanted device that counts down to when she'll meet the love of her life. Thematically its similar to Eternal Sunshine of the Spotless Mind which similarly adds a scifi device to society in order to examine the value of failed relationships on a persons life.
PermalinkCommentsmovie review netflix TiMER

PowerShell Integration Into Visual Studio

2010 Jun 22, 1:49"The PowerGUI Visual Studio Extension adds PowerShell IntelliSense support to Visual Studio."PermalinkCommentstechnical powershell visual-studio microsoft programming shell ide

New Paintings Page: Ward Shelley

2010 Feb 4, 2:07Infographic oil paintings of things like the historical influences of avant garde or the life of Frank Zappa.PermalinkCommentsart design visualization information gallery infographics painting ward-shelley via:infosthetics

ASCIImeo, Videos in Text - peter nitsch.net

2010 Jan 18, 3:22PermalinkCommentsvideo ascii humor text

Cheap Multiplayer Tricks for New Super Mario Bros. Wii

2010 Jan 5, 1:47

The New Super Mario Bros. Wii is a great game. Its the fun of old school Mario with the addition of great graphics and the kind of multiplayer I've wanted for Mario since playing the original as a child: its got up to four player simultaneous cooperative multiplayer. I recommend it to anyone who has enjoyed Mario in the past. Watch this amazing video of level 1-3 you can unlock in the game.

As noted elsewhere, multiple players attempting to navigate platforms, grab power ups, and throw turtle shells creates new challenges but along with that there's new ways to be incredibly cheap.

Jumping Higher
A second player means a head one can jump on to reach higher locations. Jump on your friend's head at the apex of their jump while holding down the jump button yourself for maximum jumping. In the game you can also grab other players and hold them over your head. This is useful for reaching the top of the flagpole at the end of levels. On that same line, if the player you grab has a flying cap you can now use them to fly in the same manner you would use a flying block which makes it easy to get two players to the top of the finish flagpole if only one of you has a flying cap.
Power-Ups
Normal power-up blocks now spawn enough power-ups for everyone. A mushroom is spawned for each small player and full power-ups for the rest, except in the case everyone is small: then one of the power-ups is a full power-up. If there's two players and you're both small, the full power-up always jumps out of the block to the right. Some hidden power-up blocks only give out one power-up and in that case its a mushroom or not based on the player who hits the block - so be sure that a big player hits that if you have one.
Death & Bubbles
When a player dies but at least one other player lives the dead player comes back in a limbo bubble from which they must be released before they may play again. Because of this, in a tough spot you can send one player in and leave a second behind. If the first dies you don't lose your place in the level and the first comes back in a bubble ready to try again. For instance, if you're trying to get the last star coin in 2-1 which sits just above the abyss, one player can just jump to their death for it and as long as another player lives you've collected the coin. However you need not sacrifice your life to do this: you can press down and 'a' to force yourself into a bubble saving yourself from death. This is true in general as long as you have enough time to see your death coming. This is also useful if one player runs ahead to the right. The screen will expand a bit but then it will just move to the right following the player in the lead. Players left behind walls or now forced into lava pits will die unless they use the bubble.
Misc.
  • If all players hit the ground at the same time from a ground pound it acts like hitting a pow block, killing the enemies on the screen.
  • If you hold a player who has a projectile power over your head they can still use their power.
  • Bubbles can be popped by hitting them with your fire or ice projectiles as well as thrown shells or blocks.
  • All players get the extra lives from anyone collecting 100 coins or finishing a level with more than 7 enemies on the screen.
PermalinkCommentsmultiplayer mario wii

English Shellcode

2009 Nov 27, 6:10"What follows is a brief description of the method we have developed for encoding arbitrary shellcode as English text. This English shellcode is completely self-contained, i.e., it does not require an external loader, and executes as valid IA32 code."PermalinkCommentssecurity polyglot intel paper research programming hack obfuscation english language technical system:filetype:pdf system:media:document

PowerShell Scanning Script

2009 Jun 27, 3:42

I've hooked up the printer/scanner to the Media Center PC since I leave that on all the time anyway so we can have a networked printer. I wanted to hook up the scanner in a somewhat similar fashion but I didn't want to install HP's software (other than the drivers of course). So I've written my own script for scanning in PowerShell that does the following:

  1. Scans using the Windows Image Acquisition APIs via COM
  2. Runs OCR on the image using Microsoft Office Document Imaging via COM (which may already be on your PC if you have Office installed)
  3. Converts the image to JPEG using .NET Image APIs
  4. Stores the OCR text into the EXIF comment field using .NET Image APIs (which means Windows Search can index the image by the text in the image)
  5. Moves the image to the public share

Here's the actual code from my scan.ps1 file:

param([Switch] $ShowProgress, [switch] $OpenCompletedResult)

$filePathTemplate = "C:\users\public\pictures\scanned\scan {0} {1}.{2}";
$time = get-date -uformat "%Y-%m-%d";

[void]([reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll"))

$deviceManager = new-object -ComObject WIA.DeviceManager
$device = $deviceManager.DeviceInfos.Item(1).Connect();

foreach ($item in $device.Items) {
        $fileIdx = 0;
        while (test-path ($filePathTemplate -f $time,$fileIdx,"*")) {
                [void](++$fileIdx);
        }

        if ($ShowProgress) { "Scanning..." }

        $image = $item.Transfer();
        $fileName = ($filePathTemplate -f $time,$fileIdx,$image.FileExtension);
        $image.SaveFile($fileName);
        clear-variable image

        if ($ShowProgress) { "Running OCR..." }

        $modiDocument = new-object -comobject modi.document;
        $modiDocument.Create($fileName);
        $modiDocument.OCR();
        if ($modiDocument.Images.Count -gt 0) {
                $ocrText = $modiDocument.Images.Item(0).Layout.Text.ToString().Trim();
                $modiDocument.Close();
                clear-variable modiDocument

                if (!($ocrText.Equals(""))) {
                        $fileAsImage = New-Object -TypeName system.drawing.bitmap -ArgumentList $fileName
                        if (!($fileName.EndsWith(".jpg") -or $fileName.EndsWith(".jpeg"))) {
                                if ($ShowProgress) { "Converting to JPEG..." }

                                $newFileName = ($filePathTemplate -f $time,$fileIdx,"jpg");
                                $fileAsImage.Save($newFileName, [System.Drawing.Imaging.ImageFormat]::Jpeg);
                                $fileAsImage.Dispose();
                                del $fileName;

                                $fileAsImage = New-Object -TypeName system.drawing.bitmap -ArgumentList $newFileName 
                                $fileName = $newFileName
                        }

                        if ($ShowProgress) { "Saving OCR Text..." }

                        $property = $fileAsImage.PropertyItems[0];
                        $property.Id = 40092;
                        $property.Type = 1;
                        $property.Value = [system.text.encoding]::Unicode.GetBytes($ocrText);
                        $property.Len = $property.Value.Count;
                        $fileAsImage.SetPropertyItem($property);
                        $fileAsImage.Save(($fileName + ".new"));
                        $fileAsImage.Dispose();
                        del $fileName;
                        ren ($fileName + ".new") $fileName
                }
        }
        else {
                $modiDocument.Close();
                clear-variable modiDocument
        }

        if ($ShowProgress) { "Done." }

        if ($OpenCompletedResult) {
                . $fileName;
        }
        else {
                $result = dir $fileName;
                $result | add-member -membertype noteproperty -name OCRText -value $ocrText
                $result
        }
}

I ran into a few issues:

PermalinkCommentstechnical scanner ocr .net modi powershell office wia

James O'Neill's blog : Borrowing from Windows Explorer in PowerShell part 2: extended properties

2009 Jun 26, 8:59"When I stated looking at what could be done using explorer objects from PowerShell I 'discovered' the extended properties."PermalinkCommentsshell windows powershell tutorial code programming explorer technical

Coding4Fun : Look at me! Windows Image Acquisition

2009 Jun 20, 9:43How to use the WIA APIs in C#. WIA is Windows API to get images from scanners and cameras. And, as I found out, if you want to use the API in PowerShell try '$deviceManager = new-object -ComObject WIA.DeviceManager'PermalinkCommentsvideo scanner api wia csharp howto programming camera image photo .net webcam technical

Issue 9860 - chromium - ChromeHTML URI handler vulnerability - Google Code

2009 May 3, 10:26Seems very similar to that ShellExecute/Firefox app URL protocol handler exploit last year. "A vulnerability in the ChromeHTML URI handler allows an attacker to bypass the Same Origin Policy for any site and also enumerate victims files and directories. When loaded in Internet Explorer, a specially crafted HTML page can launch Google Chrome with an arbitrary URI without requiring any user interaction."PermalinkCommentsexploit security google chrome browser web url protocol

Fallout 3 'Broken Steel' DLC Preview - Shacknews - PC Games, PlayStation, Xbox 360 and Wii video game news, previews and downloads

2009 Apr 21, 1:28Fallout 3's May 5th DLC removes old ending, adds new quests, new levels, new perks. Sounds good! "In a nutshell, Broken Steel will remove the game's ending entirely, with Bethesda's Pete Hines saying simply to fans that called for an open-ended resolution, "We got the idea." Players will still have to make the final choice, but following that climax the game will continue, presenting new epilogue quests, another 10 levels to gain, and new perks, monsters and achievements to keep the climb interesting."PermalinkCommentsgame videogame news fallout3 fallout

Command-line Fu - The best UNIX commands on the web

2009 Mar 23, 9:35Ohhh some nice ones in here. "Command-Line-Fu is the place to record those command-line gems that you return to again and again."PermalinkCommentsshell unix linux cli howto tips via:swannman

Windows PowerShell Core

2008 Nov 19, 3:34PowerShell function syntax and helpPermalinkCommentspowershell reference microsoft msdn function shell

Tab Expansion in PowerShell

2008 Nov 18, 6:38

PowerShell gives us a real CLI for Windows based around .Net stuff. I don't like the creation of a new shell language but I suppose it makes sense given that they want something C# like but not C# exactly since that's much to verbose and strict for a CLI. One of the functions you can override is the TabExpansion function which is used when you tab complete commands. I really like this and so I've added on to the standard implementation to support replacing a variable name with its value, tab completion of available commands, previous command history, and drive names (there not restricted to just one letter in PS).

Learning the new language was a bit of a chore but MSDN helped. A couple of things to note, a statement that has a return value that you don't do anything with is implicitly the return value for the current function. That's why there's no explicit return's in my TabExpansion function. Also, if you're TabExpansion function fails or returns nothing then the builtin TabExpansion function runs which does just filenames. This is why you can see that the standard TabExpansion function doesn't handle normal filenames: it does extra stuff (like method and property completion on variables that represent .Net objects) but if there's no fancy extra stuff to be done it lets the builtin one take a crack.

Here's my TabExpansion function. Probably has bugs, so watch out!


function EscapePath([string] $path, [string] $original)
{
    if ($path.Contains(' ') -and !$original.Contains(' '))
    {
        '"'   $path   '"';
    }
    else
    {
        $path;
    }
}

function PathRelativeTo($pathDest, $pathCurrent)
{
    if ($pathDest.PSParentPath.ToString().EndsWith($pathCurrent.Path))
    {
        '.\'   $pathDest.name;
    }
    else
    {
        $pathDest.FullName;
    }
}

#  This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.

function TabExpansion($line, $lastWord)
{
    switch -regex ($lastWord)
    {
         # Handle property and method expansion...
         '(^.*)(\$(\w|\.) )\.(\w*)$' {
             $method = [Management.Automation.PSMemberTypes] `
                 'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
             $base = $matches[1]
             $expression = $matches[2]
             Invoke-Expression ('$val='   $expression)
             $pat = $matches[4]   '*'
             Get-Member -inputobject $val $pat | sort membertype,name |
                 where { $_.name -notmatch '^[gs]et_'} |
                 foreach {
                     if ($_.MemberType -band $method)
                     {
                         # Return a method...
                         $base   $expression   '.'   $_.name   '('
                     }
                     else {
                         # Return a property...
                         $base   $expression   '.'   $_.name
                     }
                 }
             break;
          }

         # Handle variable name expansion...
         '(^.*\$)([\w\:]*)$' {
             $prefix = $matches[1]
             $varName = $matches[2]
             foreach ($v in Get-Childitem ('variable:'   $varName   '*'))
             {
                 if ($v.name -eq $varName)
                 {
                     $v.value
                 }
                 else
                 {
                    $prefix   $v.name
                 }
             }
             break;
         }

         # Do completion on parameters...
         '^-([\w0-9]*)' {
             $pat = $matches[1]   '*'

             # extract the command name from the string
             # first split the string into statements and pipeline elements
             # This doesn't handle strings however.
             $cmdlet = [regex]::Split($line, '[|;]')[-1]

             #  Extract the trailing unclosed block e.g. ls | foreach { cp
             if ($cmdlet -match '\{([^\{\}]*)$')
             {
                 $cmdlet = $matches[1]
             }

             # Extract the longest unclosed parenthetical expression...
             if ($cmdlet -match '\(([^()]*)$')
             {
                 $cmdlet = $matches[1]
             }

             # take the first space separated token of the remaining string
             # as the command to look up. Trim any leading or trailing spaces
             # so you don't get leading empty elements.
             $cmdlet = $cmdlet.Trim().Split()[0]

             # now get the info object for it...
             $cmdlet = @(Get-Command -type 'cmdlet,alias' $cmdlet)[0]

             # loop resolving aliases...
             while ($cmdlet.CommandType -eq 'alias') {
                 $cmdlet = @(Get-Command -type 'cmdlet,alias' $cmdlet.Definition)[0]
             }

             # expand the parameter sets and emit the matching elements
             foreach ($n in $cmdlet.ParameterSets | Select-Object -expand parameters)
             {
                 $n = $n.name
                 if ($n -like $pat) { '-'   $n }
             }
             break;
         }

         default {
             $varNameStar = $lastWord   '*';

             foreach ($n in @(Get-Childitem $varNameStar))
             {
                 $name = PathRelativeTo ($n) ($PWD);

                 if ($n.PSIsContainer)
                 {
                     EscapePath ($name   '\') ($lastWord);
                 }
                 else
                 {
                     EscapePath ($name) ($lastWord);
                 }
             }

             if (!$varNameStar.Contains('\'))
             {
                foreach ($n in @(Get-Command $varNameStar))
                {
                    if ($n.CommandType.ToString().Equals('Application'))
                    {
                       foreach ($ext in @((cat Env:PathExt).Split(';')))
                       {
                          if ($n.Path.ToString().ToLower().EndsWith(($ext).ToString().ToLower()))
                          {
                              EscapePath($n.Path) ($lastWord);
                          }
                       }
                    }
                    else
                    {
                        EscapePath($n.Name) ($lastWord);
                    }
                }

                foreach ($n in @(Get-psdrive $varNameStar))
                {
                    EscapePath($n.name   ":") ($lastWord);
                }
             }

             foreach ($n in @(Get-History))
             {
                 if ($n.CommandLine.StartsWith($line) -and $n.CommandLine -ne $line)
                 {
                     $lastWord   $n.CommandLine.Substring($line.Length);
                 }
             }

             # Add the original string to the end of the expansion list.
             $lastWord;

             break;
         }
    }
}

PermalinkCommentscli technical tabexpansion powershell
Older EntriesNewer Entries Creative Commons License Some rights reserved.