Powershell History Remove Duplicate Commands

alt=“powershell history commands”

When running commands within PowerShell, the history of commands may contain duplicated commands. To run a command contained within the commands history, you use the up arrow key to scroll up to the required command. If the commands are many and duplicated, it may require a bit of effort to get to the required command.

In Windows PowerShell 5.0, you can prevent duplication of commands within the history by running the following command in PowerShell:

    Set-PSReadLineOption HistoryNoDuplicates:$True

The above command will prevent duplication of commands within the history in the current session.

If you would like the above command to be the default behaviour for PowerShell, then you have to add this command to the PowerShell profile.

Steps

  1. To display the path to the Windows PowerShell profile, type the following command in PoweShell:

        $profile
    
  2. Test if a PowerShell profile has been created on the system by the following command:

        test-path $profile
    

    If the profile exists within the system, the command will give a response of Yes, otherwise the response will be False

  3. If the response is false, create Windows PowerShell profile by typing the following command otherwise skip to the next step:

        new-item -path $profile -itemtype file -force
    

    NOTE: Running the above command while the response is Yes will overwrite the existing PowerShell file.

  4. Open the profile with Notepad by typing the following:

        notepad $profile
    
  5. Insert the following command in the profile file to prevent PowerShell history duplication:

        Set-PSReadLineOption HistoryNoDuplicates:$True
    
  6. Save the profile file

  7. Close the current session of PowerShell.

The following are the set of commands and outputs as contained within the above steps.

PS C:\Users\user1> $profile
C:\Users\user1\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
PS C:\Users\user1> test-path $profile
False
PS C:\Users\user1> new-item -path $profile -itemtype file -force


    Directory: C:\Users\user1\Documents\WindowsPowerShell


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       11/17/2017   3:48 AM              0 Microsoft.PowerShell_profile.ps1


PS C:\Users\user1> notepad $profile
PS C:\Users\user1>