2
1

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の環境変数にパスを追加する関数(PowerShell)

Last updated at Posted at 2023-12-16

ユーザー環境変数へパスを追加する方法は以下

$new_dir = "C:\HOGE"

$new_path = [Environment]::GetEnvironmentVariable("Path", "User")
$new_path += ";$new_dir"
[Environment]::SetEnvironmentVariable("Path", $new_path, "User")

こんなん毎回入力してられないので関数を作っておku

関数

下記をPowerShellの.bashrc的なファイルにコピペしておく
そのパスは$profileで確認できるからcode $profileするとVSCodeで編集できるよ

function add_path {
    param ([string]$new_path)

    $new_path = $new_path -replace '/', '\'

    # フォルダが存在しないなら終了
    if (-not (Test-Path -Path $new_path -PathType Container)) {
        Write-Output  "指定されたパスのフォルダは存在しません: $new_path"
        return
    }

    # 環境変数Pathを取得 (ユーザー)
    $user_path = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::User)

    # すでに追加済みであれば終了
    if ($user_path -like "*$new_path*") {
        Write-Output  "パスはすでに環境変数に存在します: $new_path"
        return
    }

    # パスを追加
    if (-not $user_path.EndsWith(";")) {
      $user_path += ";"
    }
    $user_path += $new_path
    [Environment]::SetEnvironmentVariable("Path", $user_path, [EnvironmentVariableTarget]::User)

    Write-Output "新しいパスをユーザー環境変数に追加しました: $new_path"
}

function show_path {
  [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::User).Split(";")
}

自分用なんだしPowerShellのコーディングスタイルなんて気にしない

使う

C:\flutter\bin>を追加してみる

PS C:\flutter\bin> add_path C:\flutter\bin
新しいパスをユーザー環境変数に追加しました: C:\flutter\bin

PS C:\flutter\bin> show_path
C:\Users\inarb\AppData\Local\pnpm
C:\Users\inarb\AppData\Local\Programs\Python\Python312\Scripts\
C:\Users\inarb\AppData\Local\Programs\Python\Python312\
C:\Users\inarb\AppData\Local\Programs\Python\Launcher\
C:\Users\inarb\AppData\Local\Microsoft\WindowsApps
C:\Users\inarb\AppData\Local\Programs\Microsoft VS Code\bin
C:\Users\inarb\AppData\Local\Microsoft\WinGet\Packages\DenoLand.Deno_Microsoft.Winget.Source_8wekyb3d8bbwe
C:\flutter\bin

PS C:\flutter\bin> add_path $(pwd).Path
パスはすでに環境変数に存在します: C:\flutter\bin

いい感じ

参考

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?