vbapowershellwindows-10clipboard

How to clear Windows 10 Clipboard history via VBA and PowerShell command


I want to clear Windows Operating System Clipboard history via VBA and PowerShell command.

I am a Windows 10 user.


Solution

  • Prerequisite:


    There are two ways to clear the clipboard history using PowerShell:


    Invoke the clipboard history-clearing PowerShell command from VBA:

    The code below runs the PowerShell console window that is invariably created hidden, by using vbHide window style in the .Run() call.
    For troubleshooting, switch to vbNormalFocus, and place -NoExit before -Command in the powershell.exe call.

    Dim exitCode as Integer
    
    ' Run the PowerShell command hidden (vbHide), synchronously (True)
    ' and obtain its exit code.
    exitCode = CreateObject("WScript.Shell").Run( _
     "powershell.exe -NoProfile -Command [Windows.ApplicationModel.DataTransfer.Clipboard, Windows, ContentType = WindowsRuntime]::ClearHistory()", _
     vbHide, _
     True _
    )
    
    If exitCode = 0 Then ' Command succeeded.
        ' Report success.
        MsgBox "Successfully cleared the clipboard history.", vbInformation
    Else ' Command indicated failure.
        MsgBox "An unexpected error occurred while trying to clear the clipboard history", vbExclamation
    End If
    

    If, for some reason, the powershell.exe call can not be made from the UI thread of the VBA-hosting application, you'll need to use the Restart-Service method, and doing so then invariably requires elevation.

    Dim exitCode as Integer
    
    ' Run the PowerShell command with elevation, synchronously, 
    ' and obtain the exit code.
    exitCode = CreateObject("WScript.Shell").Run("powershell.exe Start-Process -Wait -Verb RunAs -WindowStyle Hidden powershell.exe 'Restart-Service cbdhsvc_*'", vbHide, True)
    
    If exitCode = 0 Then ' Command succeeded.
        ' Display the output.
        MsgBox "Successfully cleared the clipboard history.", vbInformation
    Else ' Command indicated failure.
        MsgBox "An unexpected error occurred while trying to clear the clipboard history", vbExclamation
    End If