【PowerShell】sendkeys で日本語を送りたい

以前、こんな投稿をしました。

【PowerShell】WEB ページをアーカイブする

この投稿の中では、PowerShell を使用して WEBサイトを MHT ファイルに保存する方法について書いたわけですが、ある方から質問をいただきました。

ファイル名を日本語で入力するにはどうしたらよいか?」

なんとするどい質問でしょう。

そうなんです。vbs 使いには昔から有名な話ですが、sendkeys メソッドって日本語が正しく送れないのです。

例えば以下のようなスクリプトを実行したとします。これは、$url を mht 形式で保存するスクリプトなのですが、「Web ページの保存」ダイアログに対して Sendkeys メソッドでキーシーケンスを送っています。

$url = "https://www.microsoft.com/" $title = "abcdefg1234 マイクロソフト 安納 順一" $code = '$WShell = New-Object -comobject WScript.Shell; ' $code = $code + '$WShell.AppActivate(''Web ページの保存'', $true); ' $code = $code + '$WShell.SendKeys(''%T'') ; ' $code = $code + '$WShell.SendKeys(''{DOWN}'') ; ' $code = $code + '$WShell.SendKeys(''{UP}'') ; ' $code = $code + '$WShell.SendKeys(''{UP}'') ; ' $code = $code + '$WShell.SendKeys(''{DOWN}'') ; ' $code = $code + '$WShell.SendKeys(''{ENTER}'') ; ' $code = $code + '$WShell.SendKeys(''%N'') ; ' $code = $code + '$WShell.SendKeys('''+ $title + ''') ; ' $code = $code + '$WShell.SendKeys(''%S'')' $ie = New-Object -ComObject InternetExplorer.Application $ie.Navigate( $url ) while ($ie.ReadyState -ne 4) { Start-Sleep -Milliseconds 100} Start-Process powershell.exe -argument ('-version 2.0 -noprofile -windowstyle hidden -command "{0}"' -f $code) $ie.ExecWB(4,0,$null,[ref]$null)

これを実行すると、ファイル名には以下のような文字列が入力されます。

image

そう、日本語が正しく入らないのですねぇ。

じゃ、どうするか。

検索エンジンを使っていただくといろんな回答が出てきますが、一番簡単なのは clip.exe でしょう。っていうか、書式がシンプルなので個人的に好きです。

clip.exe を使用すると、文字列をクリップボードにコピーすることができます。以下のように使います。

echo "ほげほげ" | clip.exe

これで「ほげほげ」という文字列がクリップボードにコピーされたので、^v を使ってペーストすればよいわけですね。なお「^」は Controlキーのシーケンスです。

スクリプトを修正すると以下の通りです。

$url = "https://www.microsoft.com/" $title = "abcdefg1234 マイクロソフト 安納 順一" $title | clip.exe $code = '$WShell = New-Object -comobject WScript.Shell; ' $code = $code + '$WShell.AppActivate(''Web ページの保存'', $true); ' $code = $code + '$WShell.SendKeys(''%T'') ; ' $code = $code + '$WShell.SendKeys(''{DOWN}'') ; ' $code = $code + '$WShell.SendKeys(''{UP}'') ; ' $code = $code + '$WShell.SendKeys(''{UP}'') ; ' $code = $code + '$WShell.SendKeys(''{DOWN}'') ; ' $code = $code + '$WShell.SendKeys(''{ENTER}'') ; ' $code = $code + '$WShell.SendKeys(''%N'') ; ' $code = $code + '$WShell.SendKeys(''^v'') ; ' $code = $code + '$WShell.SendKeys(''%S'')' $ie = New-Object -ComObject InternetExplorer.Application $ie.Navigate( $url ) while ($ie.ReadyState -ne 4) { Start-Sleep -Milliseconds 100} Start-Process powershell.exe -argument ('-version 2.0 -noprofile -windowstyle hidden -command "{0}"' -f $code) $ie.ExecWB(4,0,$null,[ref]$null)

これで、めでたくファイル名に日本語が入りました。

image

このように、.NET Framework を駆使しなくても、1行追加するだけで実装できてしまいます。

clip.exe コマンド、便利ですねぇ。