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

2 min read Original article โ†—

Li Chun

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

2. 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 the WSL-PowerShell pipe right.