Handy little function: Create-Script
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.
No related posts.
2 Responses to Handy little function: Create-Script
Tags
Active Directory API bind order cleanup cluster CPU Custom Fields datastores description device management directory tree errors Event Log file name filter Fun function HA IT known issues License Server LUN multipath NIC objects Oneliner portgroups PowerCLI PowerShell profile recursive Registry Scripts security session share snapshots SQL Stat VI Toolkit VMware vSphere WMI WSUS ZenArchives
- July 2012
- July 2011
- February 2011
- January 2011
- December 2010
- May 2010
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008





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.
Hi Derek,
Thanks! And you’re welcome.
You’ve made some nice customizations. Thanks for commenting!
Hugo