2

I am curious to know if we can do this in Powershell.

with Out-File command we can pipe it to get output written to a file. That way I can send all my history commands to a text file.

The Question is Can I send my history commands to a text file every time I exit?
I don't know if this would be of big help but sometimes if you wrote some one liners and you quit the PS console accidentally then all the history commands will be saved to a text file just like recent chat conversations.

2

3 Answers 3

5

You can use start-transcript -path .\console.txt -append in you $profile to have in a txt file all console actions, not just the History but the returns of the commands too.

Sign up to request clarification or add additional context in comments.

4 Comments

That really sounds interesting. I did a Get-Help and it says, "Creates a record of all or party of a Windows PS session in a text file".
Yes! I use this command in my $profile for the same reasons in your question!
I don't anymore, but putting this in my profile was a huge help when I started learning PS.
One thing to note about Start-Transcript is that it doesn't capture output of external executables which write directly to the shell. In order to capture output from those you'll need to force stdout through the PowerShell host output API like this ping.exe localhost 2>&1 | out-host.
2

Another possibility:

function start-histcap {
clear-history
$host.enternestedprompt()
get-history | out-file c:\testfiles\commandhist.txt -append
}

Run start-histcap, and you'll be at a nested prompt. Whatever you do there will get written to the history file when you exit that nested prompt.

Comments

1

Its hard to always catch an "exit". you can register for the onexit event but the problem is that will ONLY catch when a user types "exit" not if they hit the X or close in any other way..

Powershell profile "on exit" event?

so in the action event you just do get-history (specify a number if you need more than the default 100) and then set-content to a file...

you might be better off using Start-Transcript, but that only works in Console..

1 Comment

the powershell.exiting event is almost useless. any script you hook into will fail randomly as the runspace is actually shutting down asynchronously when this event occurs. a classic race condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.