One of the great features of Windows Powershell is the combination of the rich scripting language and the interactive shell. I often find myself playing around in the interactive shell until I know how to get the information I need. Then I start to put the code into a script for easy use. (And to share it with you, of course.) And although the shell allows for copy/paste, I wouldn’t be much of a scripting enthusiast if I didn’t want that to be easier ;)
Enter Create-Script. This little function belongs in any scripter’s profile. It copies your entire history into a file and opens it for you. Just remove the obsolete lines and add formatting and comment and your script is as good as done!

function Create-Script
{
$ScriptFile = ‘D:\scripts\newscript.ps1′
Remove-Item $ScriptFile -Confirm
ForEach ($i in (Get-History -Count 999))
{
Add-Content $ScriptFile $i.CommandLine
}
Invoke-Item $ScriptFile
}

The function re-uses the same file each time, asking for confirmation to overwrite it. Don’t forget to use Save As… to store your finished work.

I can’t wait to see the masterpieces you will create. Don’t forget to share them!
Hugo

PS: You might want to consider to increase the amount of commands kept in your history. Just set the $MaximumHistoryCount variable to the desired value.

»crosslinked«

Tagged with:
 

2 Responses to Handy little function: Create-Script

  1. Very cool function! I would always just re-type this stuff as needed. I love this!

    I did modify a couple of things in mine.

    – Rather than Invoke-Item, I am using: $psplus.OpenFile($scriptFile)

    This guarantees that the script file open in my PowerShellPlus editor.

    – I am overwriting the temp script file like this:
    if (test-path $scriptFile) {Remove-Item $scriptFile -force}

    This prevents an error from showing up if the file does not exist. Also, it forces the overwrite, which I prefer.

    Great little tool! Thank you for sharing it.

  2. admin says:

    Hi Derek,
    Thanks! And you’re welcome.
    You’ve made some nice customizations. Thanks for commenting!
    Hugo

Leave a Reply