PowerShell: Repeat Yourself with the Command "Scratch Pad"
Heres a useful snippit of code I wrote as a utility and thought I'd post up for everyone. Very often when using a command line, you need to repeat a set of commands. For example, copy several files:
copy "c:\blah.txt" "c:\otherPlace\blah.txt"
copy "c:\dev\blah.txt" "c:\otherPlace\blah2.txt"
History is okay for this, but if you have a set of commands you need to run, you need to run them each individually. Also, if you go to do something else, they'll eventually lose their spot in the command history.
To solve this, I created a "scratch pad". Nothing special, but definately useful.
new-scratch "MyFirstScratch"
copy "c:\blah.txt" "c:\otherPlace\blah.txt"
scratch
copy "c:\dev\blah.txt" "c:\otherplace\blah2.txt"
scratch
## Do some other stuff here...
get-scratch # prints out the contents of the scratch.
invoke-scratch
This scratch pad is holds a set of commands that you want to rerun later. You can then call invoke-scratch to run the scratchpad. You can have multiple scratch pads, and use them by just adding the name to the end of the function (get-scratch "MyFirstScratch"). By default all scratch pad commands will default to the last used scratch pad.
The example below shows how to shorten the sample above:
new-scratch "MyFirstScratch"
copy "c:\blah.txt" "c:\otherPlace\blah.txt"
copy "c:\dev\blah.txt" "c:\otherplace\blah2.txt"
scratch 2 # Saves the last 2 items to the scratch pad
This can be very useful for writing scripts too. the Save-Scratch command lets you export your scratch to a file.
Heres the code. Add it to your profile and go. Enjoy!
function New-Scratch($name) {
if ($global:scratchPads -eq $null) {
$global:scratchPads = @{}
}
$pad = new-object System.Collections.ArrayList
$global:scratchPads.Add($name, $pad)
$global:currentScratchPad = $pad
$global:currentScratchPadName = $name
}
function Get-Scratch($name=$null) {
if ($name -ne $null) {
$global:currentScratchPad = $global:scratchPads[$name]
$global:currentScratchPadName = $name
}
return $global:currentScratchPad
}
function Scratch([int]$count=1,$name=$null) {
if ($name -ne $null) {
$global:currentScratchPad = $global:scratchPads[$name]
$global:currentScratchPadName = $name
}
$hist = get-history
if ($name -eq $null) {
$name = $global:currentScratchPadName
}
for ($i=$hist.Length-$count; $i -lt $hist.Length; $i++) {
$global:currentScratchPad.Add($hist[$i].CommandLine) | out-null
}
}
function Invoke-Scratch($name=$null) {
if ($name -ne $null) {
$global:currentScratchPad = $global:scratchPads[$name]
$global:currentScratchPadName = $name
}
foreach ($item in $global:currentScratchPad) {
write-host ">> $item"
invoke-expression $item
}
}
function Save-Scratch($path, $name=$null) {
if ($name -ne $null) {
$global:currentScratchPad = $global:scratchPads[$name]
$global:currentScratchPadName = $name
}
$global:currentScratchPad | out-file $path
}