LoginSignup
4
3

More than 5 years have passed since last update.

Windows PowerShellでCoreutilsライクなls

Posted at

素人の備忘録。

Windows10でBashが使えるようになるそうですね。
そんな状況で今更この記事に需要があるのかよくわからないが、意外と日本語での情報が見当たらないので念のため記録しておく。

動機

PowerShellのls (Get-ChildItem) はもう少しなんとかならなかったのか。
コマンドプロンプトから何も変わっていない。

normal_ls.png

さすがにもうちょっと見栄えを良くしたい。

coreutils-like_ls.png

解決策

ぶっちゃけこちら。

code: Coreutils-style ‘ls’ for Windows Powershell

gcic-profile.ps1の中身を自分のプロファイルにコピペし、get-ChildItemColored.psm1\WindowsPowerShell\Modules\get-ChildItemColored以下に保存するだけ。

ただし、このままでは日本語のファイル/フォルダ名で表示がおかしくなる。
原因は明らかで、get-ChildItemColored.psm1の28, 29行目と131, 133行目でファイル/フォルダ名の文字数をカウントしているので、倍角文字に対応できていない。
そこで文字列のバイト数を見るように手を加える。

get-ChildItemColored.psm1_28-29行目
-if ($_.name.length -gt $w) {
+if ([System.Text.Encoding]::GetEncoding("Shift_Jis").GetByteCount($_) -gt $w) {
-$w = $_.name.length
+$w = [System.Text.Encoding]::GetEncoding("Shift_Jis").GetByteCount($_)
get-ChildItemColored.psm1_131-133行目
-write-host -nonewline "$(' '*($c.width - $fn.length - $dec))"
+write-host -nonewline "$(' '*($c.width - [System.Text.Encoding]::GetEncoding("Shift_Jis").GetByteCount($fn) - $dec))"
} else {
-write-host -nonewline -fore $(pick-color $f) "$fn$(' '*($c.width - $fn.length - $dec))"
+write-host -nonewline -fore $(pick-color $f) "$fn$(' '*($c.width - [System.Text.Encoding]::GetEncoding("Shift_Jis").GetByteCount($fn) - $dec))"

これで日本語に対応できる。

4
3
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
4
3