LoginSignup
3
3

More than 5 years have passed since last update.

[Powershell5.0]Get-Locationの出力がうまくされないときの対処方法

Last updated at Posted at 2016-05-28

どのバージョンからこうなったのかは不明ですが、Powershell5.0でGet-Locationの出力を表示させた場合の挙動がなにやらおかしかったので。

発生例

test.ps1
Get-Location
Write-Output "hoge"
Write-Host "foo"

Read-Host -Prompt "Read-Host"

上記のスクリプトファイルを R:\test 配下で実行したとき、期待するのは下記のような結果となることですが、

期待する出力
Path   
----   
R:\test
hoge
foo
Read-Host: 

実際には下記のように順番が入れ替わって出力されます。

実際の出力
foo
Read-Host: 
Path   
----   
R:\test
hoge

Read-Hostのプロンプトの後、Enterを叩いてから表示がされる形になるので、モノによってはかなりわけのわからないことに。

また、下記のように一旦変数に格納して、それを表示させた場合でも同様です。

$location = Get-Location
$location

新しいバージョンでだけ発生する問題のようです。
"powershell -Version 2.0"と指定してPowershellを起動し実行した場合は期待通り出力がされます。
ちなみに$PWDを参照した場合も同じ事になるので、PathInfo型の処理がおかしいのかも。

対処方法

Get-Locationの出力を表示させる場合はGet-Location | Format-TableのようにFormat-*にパイプしてやります。

test.ps1
Get-Location | Format-Table
Write-Output "hoge"
Write-Host "foo"

Read-Host -Prompt "Read-Host"
出力結果
Path   
----   
R:\test


hoge
foo
Read-Host: 

これで一応想定通りの順番で出力がされます。
しかしなぜこれでうまくいくのかわからない

3
3
1

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
3
3