LoginSignup
2

More than 5 years have passed since last update.

powershell 実行中に PATH 環境変数へカレントディレクトリーを追加する簡単な方法

Last updated at Posted at 2016-01-07

はじめに

記事を書いた後にコメントで他の方法や注意点など議論を寄せて頂いています。記事本体と併せてコメント欄もどうぞご覧下さい。

背景

powershell を実行中に PATH 環境変数へカレントディレクトリーを追加したくなった。しかし powershell 実行中の pwd エイリアスや [System.IO.Directory]::GetCurrentDirectory() はどうも使い勝手が悪い。そこで簡単な方法はどうしたら良いか考えたので整理したい。

簡単な方法

cmd /c cd の結果を linux 等で一般的な pwd 相当の実行結果として使い $env:path を更新する。

$env:path = "$(cmd /c cd);" + $env:path

与えるものは単なる文字列なので適当な相対パスを与えたい場合は次のようにパスを追記すれば良い。

$env:path = "$(cmd /c cd)\\some_path\\bin;" + $env:path

付録: トリックについて

カレントディレクトリーの取得を cmd /c cd で行うのは powershell をせっかく使っているのに何だか残念な気持ちになるかもしれない。これを「簡単な方法」として用いた理由は2つ。

理由 1. powershellpwd は余計な表示が入って邪魔。

PS C:\Users\usagi\tmp> pwd

Path
----
C:\Users\usagi\tmp


PS C:\Users\usagi\tmp>

理由 2. powershell[System.IO.Directory]::GetCurrentDirectory() を直接呼んでも意図しないディレクトリーが得られる。(+ついでに書くのだるい。)

以下は一見すると意図する pwd 的に近い結果が得られているが、致命的な事にカレントディレクトリーではない。

PS C:\Users\usagi\tmp> [System.IO.Directory]::GetCurrentDirectory()
C:\Users\usagi
PS C:\Users\usagi\tmp>

References

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