Unix pipe to clipboard with WSL, and in UTF-8

2024-04-17

WSL is good, it will be even better if we can pipe stdout directly into Windows host’s clipboard. Just like

    ./myscript.sh | to-my-clipboard.sh

Note that xclip requires X, so it is not an option. From WSL, we have direct access to Windows executables. The easiest method would be using clip.exe:

    ./myscript.sh | clip.exe

The method works fine if you don’t touch CJK characters or emojis. clip.exe didn’t handle the encoding well since the default codepage in Windows is not 65001(UTF-8). The command below would probably break

    echo 😀 | clip.exe

The solution is to provide clip.exe with an environment in which the encoding can be specified. PowerShell is a natural fit for the job in Windows. We can do the trick with two simple steps:

  1. Setup PowerShell profile The PowerShell profile is like .bashrc but for PowerShell. You may need to create a .ps1 file in the location of $PROFILE. echo $PROFILE in PowerShell would give you the full path of the profile, something like C:\Users\\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 . Ensure the path and notepad.exe $PROFILE let you edit the file with notepad. Put the content in the file
    chcp 65001 |  Out-Null
  1. Use clip.exe with PowerShell in WSL With the setup above, you may simply pipe the result of any command from WSL to your Windows.
    # with powershell 5.1 
    echo 😀 | powershell.exe -Command clip.exe
    # with powershell 7.x
    echo 😀 | pwsh.exe -Command clip.exe

You can also wrap it in a bash script

    echo 'pwsh.exe -Command clip.exe' > ~/.local/bin/clip.sh
    chmod +x ~/.local/bin/clip.sh

Then you can write

    echo 😀 | clip.sh

Note that, I have also looked into Set-Clipboard cmdlet in the PowerShell. But I never got to escape the content passing through WSL-PowerShell pipe right.