Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run command without adding it to the history

Tags:

powershell

I am trying to create a clean history of commands for a specific task. As a result, I would like to specific which commands to keep in history and which commands not to keep. For instance, to prevent a command from going into the history, I would like to be able to run something like this:

cls -no-history

That would prevent cluttering the history with cls commands. For the time being, I am just running clear-history -id 7, for instance, to delete specific history items.

like image 343
Shaun Luttin Avatar asked Feb 22 '15 22:02

Shaun Luttin


2 Answers

Caution, as of Windows 10 you'll need to also remove any new entries from %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt otherwise it will still appear in the "up arrow" list of previous commands.

You can do this with a text editor.

like image 167
creanion Avatar answered Sep 23 '22 02:09

creanion


This is a really interesting question. I think I've come up with a way that will actually do this for you, but you need to define a function and then pipe the command you want out of the history into that function.

function Skip-History {
[CmdletBinding()]
param(
    [Parameter(
        ValueFromPipeline=$true
    )]
    [Object]
    $o
)
    Begin {
        $history = Get-History
    }

    Process {
        $o
    }

    End {
        Clear-History
        $history | Add-History
    }
}

To use it:

cls | Skip-History
Get-Process | Skip-History

A downside of this is that it will constantly be re-numbering your history IDs, if that matters.

Also, through further experimentation, it seems that this will not work unless you use it directly after each cmdlet in a pipeline. So if you wanted to hide Get-Process | Sort-Object you would have to call it like this:

Get-Process | Skip-History | Sort-Object | Skip-History
like image 30
briantist Avatar answered Sep 26 '22 02:09

briantist