Using PowerShell History ( Part 2 )
In my last blog, I talked about how you can increase the history buffer limit. This is very helpful if you ever want to save the commands that you may have been working on to later incorporate into your script library. I would normally save the history to a file by using the Get-History cmdlet or history alias:
1: history -c 1000 > c:\history.txt
2:
In most cases, this works without any problem until you use a very long command. For example, try typing the command below:
1: Write-Host "This is a very long line that will be truncated when enumerated by the Get-History cmdlet and will not show the whole line because it is very long."
2:
If you enumerate the history, you will get a truncated version of the command that you type like the output below:
PS C:\windows\system32> history
Id CommandLine
-- -----------
1 Write-Host "This is a very long line that will be truncated when enumerated by the Get-History cmdlet and will ...
However, we know that PowerShell keeps the full string of the command in memory because if you use the up and down arrow to go through each of the commands, it does show the full command. By default, the output from the Get-History cmdlet is displayed in a tabular data format like the way the Format-Table cmdlet display its data.
To work around this, we will need to pipe the history output into the Format-List cmdlet. Unlike the Format-Table cmdlet, the Format-List cmdlet outputs the object’s properties to each appear on a new line, thereby displaying the full data without having to truncate the string..
The CommandLine property value is what we are interested in, therefore, we will need to specify this as a parameter to the Format-List cmdlet :
PS C:\windows\system32> history | Format-List CommandLine
CommandLine : Write-Host "This is a very long line that will be truncated when enumerated by the Get-History cmdlet and
will not show the whole line because it is very long."
You can now redirect the output and save it to a file without loosing some of the commands due to the length of the string:
PS C:\windows\system32> history | Format-List CommandLine > C:\User\Joe\MyHistory.txt
Until next time. Enjoy!
Comments
- Anonymous
May 28, 2013
Excellent tip, thank you!