Writing code may be somewhat a challenge for some people. Hopefully, the more you work with PowerCLI, the easier it will become for you.
In the meantime, one of the hardest things to deal with is FINALLY figuring out the commands you were trying to get to work, only to lose it after running through your script. Ever done that? instead of working in the PowerShell ISE, or another script editor, you just keep working in the PowerCLI console and once you figure out that missing piece to your script, you get excited and run it all… Well, sometimes this is ok, other times, as you key-up through previous commands (Up-Arrow) you realize that PowerCLI won’t let you go back as far as you need to…
Been there, Done that… What do you do at that point? Did you know that PowerCLI keeps track of all the commands you run in a session? There is a PowerShell cmdlet, Get-History, that will allow you to see all the commands you have run, and it’s very easy to retrieve.
Get-History (and I’m not talking about high school)
If you’ve been a victim of what I mentioned above, you will absolutely love this little cmdlet. As you can see in the picture below, I ran the Get-History cmdlet and it returned each line of code I ran and adds a row number to it. This is good for several reasons, but let me also point out that the longer lines of code I cannot simply copy and paste again since it gets truncated, so what do we do?
By default, PowerShell saves the last 64 commands that were run. If you want to save more than that, you can raise the limit using the $MaximumHistoryCount variable: $MaximumHistoryCount = 2000
Do you think 2000 is enough? 🙂 Most likely… Ok, back on topic. Remember how I said that each row was given a row number? Right, if you see the row that you want to work with or look at again, you can do a Get-History <Row Number>: Get-History 114
You can see that the specific line was returned, but once again, it’s been truncated. We can return the full command by using the .Commandline property:
(Get-History 114).CommandLine
Ta Da! Problem solved. You can do this for the entire history as well if you remove the specific line number from the command (Get-History).CommandLine:
So next time you are in a bind because you accidentally lost that piece of working code in your session, don’t hesitate to use the Get-History cmdlet and get that code back!