After you successfully perform a task in Windows PowerShell, you can use the commands you’ve issued to create a script that automates the same task. This is a valuable feature found in most command shells. Unfortunately, it isn't always obvious how to go from a theoretical script to a real one. Even if you know approximately how to do it, the more difficult the task you've just performed, the less energy you have to figure out how to extract the script.
The process is straightforward once you know the basic steps:
- Extract the text of all the issued commands in your current PowerShell session.
- Save the extracted commands to a script file.
- Clean up the script file. Remove any commands that aren't part of the task you've performed to make it a cleaner script.
- Save it.
The most important part of this process is performing the command extraction step correctly. Copying text from the PowerShell window and pasting it into a file is likely to fail. Commands can be cut due to limited console buffering or split due to limited console line width. And you'd have garbage such as output data and command prompts to remove.
Instead of copying and pasting text, you can use the Get-History cmdlet. However, if you simply run Get-History at a command prompt, PowerShell's output formats will likely chop up the commands. So, you need to use code such as
Get-History -Count 32767 |
This code will get every command issued in the current session (up to Get-History's limit of 32,767), and save it to the file C:\tmp\demo.ps1. If you want to save the script file to a different location, simply replace C:\tmp\demo.ps1 with the path to the desired location.
This technique gives you a starter script without garbage from line breaks, prompts, and output. If you've entered commands on multiple lines, it returns all of the command text. Furthermore, if you've loaded custom functions, modules, snap-ins, or .NET assemblies in the current session, you'll have the code for these important additions in the initial script file.
You still need to perform work on the script, but you won't be trying to re-create a solution from scratch. Instead, you'll be taking code that has already performed the required task and simply removing extraneous or erroneous commands.