Huddled Masses
The internet home of Joel "Jaykul" Bennett...
Browse: Home / Creating PowerShell Scripts from your Command History

Creating PowerShell Scripts from your Command History

By Joel 'Jaykul' Bennett on 11-Apr-2008

The other day I was working on some scripts, trying to figure out how to do something new with WMI, and when I finally got it working, I started to copy and paste the commands I had typed into a script so that I could repeat the action in the future … and I realized that I could just use the Get-History cmdlet and export the CommandLine property of the history items to the clipboard! Wow, that’s such a timesaver …

Of course, once I thought of it, I figured that really, I should just write save them straight to a script, where I could delete the ones I didn’t want. Of course, I’m lazy, so I don’t want to type any more than I have to, and I figured this was worth turning into a script of it’s own! I’ve polished it a bit now, so that it automatically creates a script in my “Scripts” folder (which is included in my path) ... and in fact, I even went ahead and tweaked my Edit-File script (an idea I got from the PSCX guys) so that it accepts files from the pipeline so that I can write: save Test-Script 20 | edit to open the file right away.


## New-Script function
## Creates a new script from the most recent commands in history
##################################################################################################
## Example Usage:
##    New-Script ScriptName 4
##        creates a script from the most recent four commands
##    New-Script Clipboard -id 10,11,12,14
##        sends the the specified commands from the history to the clipboard
##    Notepad (New-Script ScriptName 20)
##        sends the most recent twenty commands to the script, and then opens the script in notepad
##################################################################################################
## As a tip, I use a prompt function something like this to get the ID into the prompt:
##
## function prompt {
##   return "`[{0}]: " -f ((get-history -count 1).Id + 1)
## }
##################################################################################################
## Revision History
## 1.0 - initial release
## 1.1 - fix bug with specifying multiple IDs
## 2.0 - use the current folder as the default instead of throwing an exception
##     - prompt to overwrite if not -Force
##################################################################################################

#function New-Script {
param(
   [string]$script=(Read-Host "A name for your script"),
   [int]$count=1,
   [int[]]$id=@((Get-History -count 1| Select Id).Id),
   [switch]$Force
)

# if there's only one id, then the count counts, otherwise we just use the ids
if($id.Count -eq 1) { 1..($count-1)|%{ $id += $id[-1]-1 } }
# Get the CommandLines from the history items...
$commands = Get-History -id $id | &{process{ $_.CommandLine }}

if($script -eq "clipboard") {
   if( @(Get-PSSnapin -Name "pscx").Count ) {
      $commands | out-clipboard
   } elseif(@(gcm clip.exe).Count) {
      $commands | clip
   }
} else {
   $folder = Split-Path $script
   if(!$folder) {
      # default to putting it in my "Windows PowerShell\scripts" folder which I have in my path...
      $folder = Join-Path (Split-Path $Profile) "Scripts"
   }
   if(!(Test-Path $folder)) {
      # if that fails, put it in the current path (on the file system)
      $folder = Get-Location -PSProvider "FileSystem"
   }
   # add the ps1 extension if it's not already there ...
   $file = Join-Path $folder (Split-Path $script -leaf)
   if(!(([IO.FileInfo]$file).Extension)) {
      $file = "$file.ps1"
   }
   # write an error message if the file already exists, unless -Force
   if((Test-Path $file) -and (!$Force)) {
      Write-Error "The file already exists, do you want to overwrite?"
   }
   # and confirm before setting the content if the file already exists, unless -Force
   $commands | set-content $file -Confirm:((Test-Path $file) -and (!$Force))
   Get-Item $file
}
#}

There’s way more script that is strictly needed here, but it’s mostly because I wanted to make typing the script extension and path optional, since I put almost all of my scripts in the same scripts folder, and the extension is always the same.

As you can see, you can choose to just grab the most recent X commands, or you can choose specific commands by id that you want to capture in the script. You can also output them to the clipboard, as long as you either have the PSCX snapin with out-clipboard loaded, or you have clip.exe (which is not included on XP).

This version of this script is in the PowerShell repository and if you make any improvements, you can submit them through the correction or amendment form …

Similar Posts:

  • What Scope Am I In?
  • Get-Command in PowerShell 3 (NOTE: CTP2 Bug causes module loading)
  • Working with multiple versions of PowerShell Modules
  • PowerShell 3 – Finally on the DLR!
  • More Custom Attributes for PowerShell (Parameter Transformation)

Posted in Huddled | Tagged Clipboard, Get-History, PowerShell, Scripting

« Previous Next »

Lijit Search

Tags

.Net .Net 2008 Scripting Games Automation Bugs Design Development Funny Gadgets GeoShell GUI Huddled Masses Internet licensing Microsoft Modules My Software News Personal PInvoke Pipeline Politics PoshCode PoshConsole PowerBoots PowerShell PowerShell Functions PowerTips Rants Recommender Repository Scripting ShowUI Software Solutions Textile Tips User Group UserInterface WalkThrough WebHosting Windows 7 WordPress WPF Xml

About Huddled Masses

This is web site is dedicated to the musings of Joel Bennett (aka Jaykul) about technology, software, software development, the web, and the world.

Any resemblance of the views expressed and the views of my employer, my terminal, or the view out my window are purely coincidental. The resemblance between them and my own views is non-deterministic. The question of the existence of views in the absence of anyone to hold them is left as an exercise for the reader.

P.S.: I occasionally link to things I think are great. When I do, I occasionally find a "referral code" so I can make a little cash. I promise that I don't link to anything just because of that cash (I wouldn't cross the street for the amount of cash those links bring in, never mind write a whole blog post) ... but I do not promise that things I link to will stay great as time passes, nor that you will agree with me about their greatness!

Archives

  • April 2012
  • February 2012
  • January 2012
  • October 2011
  • August 2011
  • July 2011
  • June 2011
  • March 2011
  • February 2011
  • January 2011

Copyright © 2012 Joel Bennett.

Powered by WordPress and Hybrid.