4
6

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 5 years have passed since last update.

PowerShell cd の罠

Posted at

PowerShell のスクリプト中で普通に cd (Set-Location) を使うことはあると思います。
だがしかし、実は、cd 後に外部コマンドを実行すると反映していない。
Set-Location ではPowerShell環境のカレントLocationを変更しているだけのようです。
PowerShellではドライブとしてファイルシステム以外も統合して扱うことに起因しているんだと思われますが、きっとだれもがハマルと思います。

実行環境のファイルシステム上のカレントも変更するように以下のようなfunctionを定義して代用しています。

SetCurrentDirectory.ps1
function Set-CurrentDirectory ($path) {
	Set-Location $path
	if ((Get-Location).Provider.Name -eq 'FileSystem') {
		[IO.Directory]::SetCurrentDirectory((Get-Location).ProviderPath)
	}
}

とりあえずfunction定義だけで、エラーチェックもなにもなしですが、これをもっとブラッシュアップしてコマンドレットにして、cd のエイリアスを置き換えると便利かもしれません。

cdのエイリアスが無ければもう少し混乱が避けられたのでは......。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?