14
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?

Windows TerminalでDBに接続する時に色変えたい

14
Posted at

はじめに

  • Windows11にWindows Terminalが標準で入るようになったのでGUIクライアントを別途入れたりせずにこれを使ってDBに接続したい
  • DBに接続する際のコマンドが長いの別名を付けたい
  • ついでに接続する環境によって自動で背景色とか変えたい
  • DB接続以外にも使えるとは思いますが上記のようなことをやる際に自分で設定している内容を記載します

環境

  • 使用するターミナルはWindows11に最初から入っているWindows Terminal
  • PowerShellのバージョンは5.1.x系
    • $PSVersionTableでバージョン確認
    • 自分で7系を入れている人はゴメンナサイ
  • 接続先DBはPostgreSQL
  • CLIのpsqlクライアント必要

やりかた

自分のPowerShellのプロファイルの確認

  • ターミナルを起動し以下のコマンドを実行
  • Get-Item $PROFILE
  • ps1ファイル(プロファイル)のパスが表示されなかった場合は以下を実行しps1ファイルを作成
  • New-Item -type file -force $profile
    • Microsoft.PowerShell_profile.ps1というファイルが作成されるはず

ps1ファイルの編集

  • テキストエディタでMicrosoft.PowerShell_profile.ps1ファイルを開き下記を追記し保存
# PostgreSQL Client Encoding
$env:PGCLIENTENCODING = "UTF8" 

# command
function psql-hoge-dev() {
    # 文字色とか背景色
    (Get-Host).UI.RawUI.ForegroundColor = "Red"
    (Get-Host).UI.RawUI.BackgroundColor = "DarkGreen" 

    # ユーザー名、DB名、接続先は適宜変更
    psql -U ユーザー -d DB名 -p 5432 -h 接続先アドレス
}
  • ちなみに使える色は次の16色
    • Black
    • DarkBlue
    • DarkGreen
    • DarkCyan
    • DarkRed
    • DarkMagenta
    • DarkYellow
    • Gray
    • DarkGray
    • Blue
    • Green
    • Cyan
    • Red
    • Magenta
    • Yellow
    • White

プロファイルの反映

  • Windows Terminalを再起動

コマンド実行

  • psql-hoge-dev
  • 背景色、文字色色が変わり接続されれば成功

もし実行できなかった時は

ポリシーを確認し場合によっては許可設定

  • Get-ExecutionPolicy -List
        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined
  • CurrentUserについてUndefinedとなっていたらPowerShellでPS1スクリプトを実行出来るように許可する
  • Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser    RemoteSigned
 LocalMachine       Undefined

まとめ

色を変えて接続した後、接続を切った時に自動でデフォルトの色に戻せないというのはあるが結構お手軽に設定できるのでいいのではないかと思った。
目立つ色にしておくと間違えないし。

以上。

14
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
14
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?