Friday, August 04, 2006

An easier way to learn/use PowerShell

When I write PowerShell stuff, I end up typing a lot on the keyboard - and using command recall a lot. When you start doing complex things, that gets quite boring. An alternative is to have a work PS1 file, editing it with notepad (or another tool) and only recall the line, that executes the PS1 file. In this way you 'only' have to ctrl-s, alt-tab, up arrow, return to execute the changes and the alt-tab back to make the next change.As I hate repeating the same actions over and over again - that is the reason I love making computers do just that - why not use PowerShell to help me? This is also an opportunity to use PowerShell for a real thing.

To do just that, I made these two functions -

function workpad {
$global:workpad = "$env:temp\workpad.ps1"
"Start workpad - execute with '. $workpad'"
notepad $workpad
}

function execute-workpad {
param([boolean]$executeFirst=$false) if ($executeFirst) {
$oldLastWriteTime=[datetime]"2000-01-01"
}
else {
$oldLastWriteTime=$(get-childitem $workpad).lastwritetime
"Waiting for change.."
}

while ($true) {
$lastWriteTime=$(get-childitem $workpad).lastwritetime
if ($lastWriteTime -eq $oldLastWriteTime) {
start-sleep -s 1
}
else {
"File changed - executing"
""
. $workpad
""
"Waiting for change.."
$oldLastWriteTime=$lastWriteTime
}
}
}
So now it is just a matter of starting the editor with workpad (and it takes you off where you left) and use execute-workpad to have the changes to the file executed automatically whenever you press ctrl-s. To break execute-workpad use ctrl-c or ctrl-break. I would have liked a version where you could use the window interactively at the same time, but I have not found a similar function to cmd's start/b (yet, I hope). Start /b is like & in the korn shell. Any feedback on this would be welcome - but keep in mind that the execution of the interactive commands must be done in the same context as the workpad script executes in, so variables can be used directly.

No comments: