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

WindowsTerminal、Windows PowerShellの設定

Last updated at Posted at 2025-07-13

はじめに

私が知っているWindowsTerminal、Windows PowerShellの設定をまとめました。設定ミスなどあるかもしれないですが、参考になれば幸いです。
※PowerShellではなくWindows PowerShellの設定です。

WindowsTerminal

以下のファイルに設定します。
%USERPROFILE%\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json

settings.json
{
  "$help": "https://aka.ms/terminal-documentation",
  "$schema": "https://aka.ms/terminal-profiles-schema",
  "actions": [
    {
      "command": "restoreLastClosed",
      "id": "User.restoreLastClosed"
    },
    {
      "command": "closeOtherPanes",
      "id": "User.closeOtherPanes"
    },
    {
      "command": "find",
      "id": "User.find"
    },
    {
      "command": {
        "action": "copy",
        "singleLine": false
      },
      "id": "User.copy.copy"
    },
    {
      "command": "paste",
      "id": "User.paste"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "cdUp\r"
      },
      "id": "User.sendInput.cdUp"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "gf\r"
      },
      "id": "User.sendInput.gf"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "gb\r"
      },
      "id": "User.sendInput.gb"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "explorer .\r"
      },
      "id": "User.sendInput.explorer"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "fav\r"
      },
      "id": "User.sendInput.fav"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "Show-CustomCommandMenu\r"
      },
      "id": "User.sendInput.CustomCommandMenu"
    },
    {
      "command": {
        "action": "sendInput",
        "input": "cd \t"
      },
      "id": "User.cdTabCompletion"
    }
  ],
  "alwaysShowTabs": true,
  "copyFormatting": "none",
  "copyOnSelect": false,
  "defaultProfile": "",//�‹��ɍ��킹�ĕύX�K�v
  "disableAnimations": true,
  "firstWindowPreference": "persistedWindowLayout",
  "focusFollowMouse": true,
  "initialCols": 150,
  "initialRows": 50,
  "keybindings": [
    {
      "id": "User.restoreLastClosed",
      "keys": "ctrl+shift+t"
    },
    {
      "id": "User.closeOtherPanes",
      "keys": "ctrl+shift+w"
    },
    {
      "id": "User.find",
      "keys": "ctrl+f"
    },
    {
      "id": "User.copy.copy",
      "keys": "ctrl+c"
    },
    {
      "id": "User.paste",
      "keys": "ctrl+v"
    },
    {
      "id": "User.sendInput.cdUp",
      "keys": "alt+up"
    },
    {
      "id": "User.sendInput.gf",
      "keys": "alt+right"
    },
    {
      "id": "User.sendInput.gb",
      "keys": "alt+left"
    },
    {
      "id": "User.sendInput.explorer",
      "keys": "ctrl+e"
    },
    {
      "id": "User.sendInput.fav",
      "keys": "ctrl+i"
    },
    {
      "id": "User.sendInput.CustomCommandMenu",
      "keys": "ctrl+k"
    },
    {
      "id": "User.cdTabCompletion",
      "keys": "ctrl+u"
    },

    {
      "id": "Terminal.SelectAll",
      "keys": "ctrl+a"
    },
    {
      "id": "Terminal.OpenNewTab",
      "keys": "ctrl+t"
    },
    {
      "id": "Terminal.ClosePane",
      "keys": "ctrl+w"
    },
    {
      "id": "Terminal.PrevTab",
      "keys": "ctrl+pgup"
    },
    {
      "id": "Terminal.NextTab",
      "keys": "ctrl+pgdn"
    },
    {
      "id": "Terminal.PrevTab",
      "keys": "ctrl+g"
    },
    {
      "id": "Terminal.NextTab",
      "keys": "ctrl+h"
    },

    {
      "id": null,
      "keys": "ctrl+shift+a"
    },
    {
      "id": null,
      "keys": "ctrl+tab"
    },
    {
      "id": null,
      "keys": "ctrl+shift+tab"
    },
    {
      "id": "Terminal.ResetFontSize",
      "keys": "vk(26)"
    },
    {
      "id": null,
      "keys": "ctrl+0"
    }
  ],
  "newTabMenu": [
    {
      "type": "remainingProfiles"
    }
  ],
  "profiles": {
    "defaults": {
      "backgroundImage": "\\gazou.png",//�‹��ɍ��킹�ĕύX�K�v
      "backgroundImageOpacity": 0.7,
      "colorScheme": "Iceberg",
      "cursorColor": "#FFFFFF",
      "cursorShape": "bar",
      "experimental.retroTerminalEffect": false,
      "font": {
        "builtinGlyphs": false,
        "face": "Consolas",
        "size": 10,
        "weight": "semi-bold"
      },
      "opacity": 90,
      "padding": "8, 8, 8, 8",
      "scrollbarState": "always",
      "showMarksOnScrollbar": true,
      "startingDirectory": ""//�‹��ɍ��킹�ĕύX�K�v
    },
    //�‹��ɍ��킹�ĕύX�K�v
    "list": [

    ]
  },
  "schemes": [
    {
      "background": "#161821",
      "black": "#161821",
      "blue": "#84A0C6",
      "brightBlack": "#6B7089",
      "brightBlue": "#91ACD1",
      "brightCyan": "#95C4CE",
      "brightGreen": "#C0CA8E",
      "brightPurple": "#ADA0D3",
      "brightRed": "#E98989",
      "brightWhite": "#D2D4DE",
      "brightYellow": "#E9B189",
      "cursorColor": "#FFFFFF",
      "cyan": "#89B8C2",
      "foreground": "#C6C8D1",
      "green": "#B4BE82",
      "name": "Iceberg",
      "purple": "#A093C7",
      "red": "#E27878",
      "selectionBackground": "#FFFFFF",
      "white": "#C6C8D1",
      "yellow": "#E2A478"
    }
  ],
  "showTabsInTitlebar": true,
  "theme": "dark",
  "themes": [],
  "useAcrylicInTabRow": true
}


Windows PowerShell

以下のファイルに設定します。
%USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Microsoft.PowerShell_profile.ps1
# =====================================================================
# 実現難しい
# ・表示されている連番数字を入力してからショートカットやenterでディレクトリ移動
# =====================================================================
# 環境に合わせて変更必要
# お気に入りpath
$script:MyFavoritePaths = @(
    "C:\",
    "C:\Users"
)
# お気に入りcommand
$script:MyCommandMenu = @(
    @{
        # クリップボードにcommit用の文字がコピーされるので、張り付けてcommitコメントを入力する
        DisplayName = "git commit"
        Commands = {
            Invoke-Expression "git add ."
            Invoke-Expression "git status"
            Set-Clipboard -Value 'git commit -m "[update] "'
        }
    },
    @{
        DisplayName = "front activate"
        Commands = {
            Invoke-Expression "cd C:\Users\; npm run dev"
        }
    },
    @{
        DisplayName = "back activate"
        Commands = {
            Invoke-Expression "cd C:\Users\; dotnet run"
        }
    }
)
# =====================================================================
# 現時点の時間でメッセージを定義
$hour = (Get-Date).Hour
$greeting = ""
if ($hour -ge 5 -and $hour -lt 12) {
    $greeting = "Good morning!"
} elseif ($hour -ge 12 -and $hour -lt 18) {
    $greeting = "Good afternoon!"
} else {
    $greeting = "Good evening!"
}

# 起動時のメッセージ
$currentDateTime = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")

Write-Host ""
Write-Host "******************************************" -ForegroundColor Yellow
Write-Host "* *                                    * *" -ForegroundColor Yellow
Write-Host "* $greeting Welcome to PowerShell!   *" -ForegroundColor Green
Write-Host "* Current Time: $currentDateTime      *" -ForegroundColor Cyan
Write-Host "* *                                    * *" -ForegroundColor Yellow
Write-Host "******************************************" -ForegroundColor Yellow
Write-Host ""

# スクリプトの区切りや、タスクの終了時に使用
# New-Separator -Char "-" -Color Blue -Length 50
function New-Separator {
    param(
        [string]$Char = "=",
        [int]$Length = 80,
        [ConsoleColor]$Color = "DarkGray"
    )
    Write-Host ($Char * $Length) -ForegroundColor $Color
}
# =====================================================================
# その他
# コマンド入力履歴を上下で辿るときにすでに入力している文字にマッチする履歴のみを辿る
# 例えば「git」と入力してから上矢印キーを押すと、「git」で始まる過去のコマンドだけが表示される
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

# 文字を入力してtabを押下すると、補完候補がリスト表示される
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete

# 履歴ファイルに同じコマンドが重複して保存されるのを防ぐ
Set-PSReadlineOption -HistoryNoDuplicates
# tab補完候補の最大表示数を20にする
Set-PSReadlineOption -CompletionQueryItems 20
# コマンド履歴を10,000件まで保存する
Set-PSReadlineOption -MaximumHistoryCount 10000

# gitブランチ名が日本語の場合の文字化けを防ぐ
[System.Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding("utf-8")
[System.Console]::InputEncoding = [System.Text.Encoding]::GetEncoding("utf-8")
$env:LESSCHARSET = "utf-8"

# 現在のディレクトリをエクスプローラーで開く
function Open-ExplorerHere {
    explorer .
}
# =====================================================================
# 移動系
# ディレクトリを移動時に元居た場所を記録するようにする
function Set-Location {
    # 既存の Set-Location コマンドレットを取得
    $originalSetLocation = Get-Command Set-Location -Type Cmdlet

    # 現在のディレクトリをディレクトリスタックに記録
    try {
        Push-Location
    } catch {
        # ディレクトリを記録できない場合(例: スタックがいっぱいの場合など)はエラーを無視
    }

    # 元の Set-Location コマンドレットを実行
    # $args を使って、ユーザーが入力した引数(移動先のパスなど)を渡します。
    & $originalSetLocation @args

    # ディレクトリ変更後、lsを再実行させるために前回のパスをリセット
    $script:LastLocation = $null
}

# 上の階層関数 (Go Up)
function cdUp {
    Push-Location # 現在地を記録(この処理を消すとエラーとなる)
    Set-Location ..
}

# 戻る関数 (Go Back)
function gb {
    try {
        Pop-Location
    } catch {
        Write-Host "No more places to return to" -ForegroundColor Yellow
    }
}


# 連番でファイルやフォルダを操作するための関数
function g {
    param(
        [Parameter(Mandatory=$true, Position=0)]
        [int]$Number
    )

    if ($Number -gt 0 -and $Number -le $script:LastLsItems.Count) {
        $selectedItem = $script:LastLsItems[$Number - 1] # 配列は0から始まるため -1

        Write-Host "`n[selected item]: $($selectedItem.Name)" -ForegroundColor Green

        if ($selectedItem.Extension -eq ".lnk" -and (Test-Path $selectedItem.FullName -PathType Leaf)) {
            # ショートカットファイルの場合
            try {
                # WScript.Shell を使用してショートカットのターゲットを解決
                $shell = New-Object -ComObject WScript.Shell
                $shortcut = $shell.CreateShortcut($selectedItem.FullName)
                $targetPath = $shortcut.TargetPath

                if (Test-Path $targetPath -PathType Container) {
                    # ターゲットがディレクトリの場合、移動
                    Write-Host "[action]: navigating to shortcut target directory..." -ForegroundColor Green
                    Set-Location $targetPath
                } elseif (Test-Path $targetPath -PathType Leaf) {
                    # ターゲットがファイルの場合、開く
                    Write-Host "[action]: opening shortcut target file..." -ForegroundColor Green
                    Invoke-Item $targetPath
                } else {
                    Write-Host "Warning: Shortcut target '$targetPath' does not exist." -ForegroundColor Yellow
                    Invoke-Item $selectedItem.FullName # エクスプローラーでショートカット自体を開く
                }
            } catch {
                Write-Host "Error processing shortcut: $($_.Exception.Message)" -ForegroundColor Red
                Invoke-Item $selectedItem.FullName # エラー時は通常通りショートカットを開く
            }
        } elseif ($selectedItem.PSIsContainer) {
            # フォルダの場合、移動
            Write-Host "[action]: moving to directory..." -ForegroundColor Green
            Set-Location $selectedItem.FullName
        } else {
            # その他のファイルの場合、開く
            Write-Host "[action]: opening a file..." -ForegroundColor Green
            Invoke-Item $selectedItem.FullName # explorer.exe と同じ動作
        }
    } else {
        Write-Host "Error: Invalid number entered, must be between 1 and $($script:LastLsItems.Count) " -ForegroundColor Red
    }
}
# =====================================================================
# お気に入りディレクトリ
function fav {
    $favorites = $script:MyFavoritePaths | Where-Object { $_.Trim() -ne "" } | Select-Object -Unique

    Write-Host "`n--- Directories ---" -ForegroundColor Yellow
    for ($i = 0; $i -lt $favorites.Count; $i++) {
        Write-Host "$($i + 1): $($favorites[$i])"
    }
    Write-Host "----------------------" -ForegroundColor Yellow
    Write-Host "Enter the number to navigate (or 'c' to cancel):" -ForegroundColor White
    $inputNum = Read-Host

    $selectedIndex = 0
    if ([int]::TryParse($inputNum, [ref]$selectedIndex)) {
        if ($selectedIndex -ge 1 -and $selectedIndex -le $favorites.Count) {
            $selectedPath = $favorites[$selectedIndex - 1]
            Write-Host "Navigating to: $selectedPath..." -ForegroundColor Cyan
            if (Test-Path $selectedPath -PathType Container) {
                Set-Location $selectedPath
                Write-Host "`nNavigated to: $selectedPath" -ForegroundColor Green
            } else {
                Write-Host "Error: The path '$selectedPath' does not exist or is not a directory." -ForegroundColor Red
            }
        } else {
            Write-Host "Invalid number. Please enter a number between 1 and $($favorites.Count)." -ForegroundColor Red
        }
    } else {
        if ($inputNum -eq "c") {
            Write-Host "Operation cancelled." -ForegroundColor Red
        } else {
            Write-Host "Operation cancelled." -ForegroundColor Red
        }
    }
}

# お気に入りコマンド
function Show-CustomCommandMenu {

    Write-Host "`n--- Commands ---" -ForegroundColor Yellow
    for ($i = 0; $i -lt $script:MyCommandMenu.Count; $i++) {
        Write-Host "$($i + 1): $($script:MyCommandMenu[$i].DisplayName)" -ForegroundColor Green
    }
    Write-Host "----------------------" -ForegroundColor Yellow
    Write-Host "Enter the number to execute a command (or 'c' to cancel):" -ForegroundColor White
    $inputNum = Read-Host

    $selectedIndex = 0
    if ([int]::TryParse($inputNum, [ref]$selectedIndex)) {
        if ($selectedIndex -ge 1 -and $selectedIndex -le $script:MyCommandMenu.Count) {
            $selectedCommand = $script:MyCommandMenu[$selectedIndex - 1]
            Write-Host "Executing: $($selectedCommand.DisplayName)..." -ForegroundColor Cyan
            & $selectedCommand.Commands # スクリプトブロックを実行
        } else {
            Write-Host "Invalid number. Please enter a number between 1 and $($script:MyCommandMenu.Count)." -ForegroundColor Red
        }
    } else {
        if ($inputNum -eq "c") {
            Write-Host "Operation cancelled." -ForegroundColor Red
        } else {
            Write-Host "Operation cancelled." -ForegroundColor Red
        }
    }
}
# =====================================================================
# コマンド入力待ちのたびに実行される機能

# ls の結果に連番を振る
# 最後に ls で表示されたアイテムのリストを保存する変数
$script:LastLsItems = @()
# 前回のパスを保存する変数(prompt 関数用)
# 起動時に ls を実行させるため、あえて null に設定
$script:LastLocation = $null

# 任意のコマンド実行後に ls を表示するための prompt 関数
function prompt {
    # 現在のパスが前回のパスと異なる場合(つまり、cdなどでディレクトリが変更された場合)
    if ($PWD.Path -ne $script:LastLocation) {
        # ls コマンドを実行し、連番を付与して表示
        # ここで連番付きのアイテムリストを作成し、後でアクセスできるように保存する
        $index = 1
        # Select-Object に PSIsContainer を追加する
        $currentItems = ls | Select-Object PSIsContainer, Extension, Name, Length, LastWriteTime, FullName

        # 連番を振りつつ、表示し、同時に $script:LastLsItems に保存
        $formattedItems = foreach ($item in $currentItems) {
            # 表示用のオブジェクトを作成
            [PSCustomObject]@{
                '#'             = $index
                'Extension'     = $item.Extension
                'Name'          = $item.Name
                'Length'        = $item.Length
                'LastWriteTime' = $item.LastWriteTime
                # Attributes と Mode は削除されました
                '_OriginalItem' = $item
            }
            $index++
        }

        # 連番付きのリストをグローバル変数に保存
        $script:LastLsItems = $formattedItems.'_OriginalItem'


        # 連番付きのリストをグローバル変数に保存
        $script:LastLsItems = $formattedItems.'_OriginalItem'

        # 表示するオブジェクトから '_OriginalItem' プロパティを削除する
        # これにより、Format-Table で出力されなくなる。
        $formattedItems | ForEach-Object {
            $_.psobject.Properties.Remove('_OriginalItem')
        }

        # フォーマットしてコンソールに出力
        $formattedItems | Format-Table -Wrap -AutoSize 4>&1 | Out-Host


        # 最後に ls を実行したパスを更新
        $script:LastLocation = $PWD.Path
    }

    # Gitブランチ名表示
    # Git リポジトリ内にいるかどうかをチェックし、ブランチ名を取得する関数
    function Get-GitBranchName {
        try {
            # Git リポジトリのルートディレクトリにいるかを確認
            # --is-inside-work-tree が true なら Git リポジトリ内
            $isGitRepo = & git rev-parse --is-inside-work-tree 2>$null
            if ($LASTEXITCODE -eq 0 -and $isGitRepo -eq "true") {
                # 現在のブランチ名を取得
                $branchName = (git rev-parse --abbrev-ref HEAD 2>$null).Trim()
                return $branchName
            }
        } catch {
            # Git コマンドが見つからない場合やエラーの場合は何もしない
            # 例外が発生してもプロンプト表示を妨げないようにする
        }
        return $null # Git リポジトリでない場合は null を返す
    }

    $gitBranch = Get-GitBranchName

    # プロンプトの構築
    $promptText = "$($PWD.Path)"

    if ($null -ne $gitBranch) {
        # Git リポジトリ内にいてブランチ名が取得できた場合
        Write-Host -NoNewline $promptText -ForegroundColor Cyan # パス部分をシアン色に
        Write-Host -NoNewline " " # パスとブランチの間のスペース
        Write-Host -NoNewline "[${gitBranch}]" -ForegroundColor Green # ブランチ名を緑色に
        Write-Host "> " -NoNewline -ForegroundColor White # 最後の "> " を白色に
    }
    else {
        # Git リポジトリ内にいない場合、通常のプロンプト
        Write-Host -NoNewline $promptText -ForegroundColor Cyan # パス部分をシアン色に
        Write-Host "> " -NoNewline -ForegroundColor White # 最後の "> " を白色に
    }

    #半角スペースを入れないと 「C:\Users [HEAD]> PS>」のように「PS>」が表示される
    return " "
}

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