1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Windows,WSL環境でのpbpaste代替決定版

Last updated at Posted at 2023-05-30

Windows上のWSLで困るのがクリップボードとのやりとり。クリップボードに送る方はclip.exeに渡せばいいけど、とりだしが大変。

以下、WSL2からWindows上のクリップボードからテキストを取り出す時の決定版。

これ

powershell.exe -command "[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding('utf-8');Get-Clipboard"

めちゃくちゃ長い。馬鹿っぽいけどこれにエイリアスでもはるしかない。

別解として以下のコマンドでもうまくいくケースはある。

powershell.exe -command "Get-Clipboard"

ただし、これをスクリプト経由で呼び出そうとすると、powershell自体のコンソールがデフォルトのSJISで吐き出そうとして実行結果を受け取る際にUTF8ベースの環境で化ける。

以下irbの中でpowershell経由でクリップボードを呼び出すサンプル。クリップボードには🐏の絵文字が入っている。

irb(main):005:0> `powershell.exe -command "Get-Clipboard"`
=> "??\r\n"
irb(main):006:0> `powershell.exe -command "[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding('utf-8');Get
Clipboard"`
=> "🐏\r\n"

エンコード指定をしないとSJISベースで吐き出そうとするので化ける。

上記方式の特徴

  • PowerShell5系でも7系でも機能する
  • WSL上からでも直接使える
  • WSL上のrubyでもWindows上のjrubyからも外部コマンド呼び出しで機能する
  • 何もインストールしないでいい

クリップボードアクセスの際にはPythonからWin32APIを呼び出してる例もあるんだけど、その方式だとWSLからは使えない。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?