Current directory apparently not current directory

Viewed 933

Running this code in ISE works.

Push-Location -Path $(Split-Path -Parent $myInvocation.MyCommand.Path)
Get-Location
$file = '.\ex.txt'
$reader = New-Object System.IO.StreamReader($file)

Running the same code in Console fails. What am I missing?

PS H:\src\powershell> .\ccount.ps1

Path
----
H:\src\powershell
New-Object : Exception calling ".ctor" with "1" argument(s): "Could not find file
'C:\src\powershell\ex.txt'."
At H:\src\powershell\ccount.ps1:9 char:11
+ $reader = New-Object System.IO.StreamReader($file)
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands
   .NewObjectCommand

How this is different from the suggested duplicate

The other question/answer does give an explanation for why PowerShell fails in this case. However, it does not give any hint as to why this works in ISE. This seems to be a significant difference between the Console and ISE host.

I am running PSVersion 5.0.10586.117 on Windows 7 Enterprise SP1.

3 Answers

The answer appears to be that Push-Location does not change [Environment]::CurrentDirectory in the console host. It does change it in ISE.

PS 09:02 \\SRV1\SH1\home\pwatson2 H:\
>Push-Location H:\src\t

PS 09:02 \\SRV1\SH1\home\pwatson2 H:\src\t
>Get-Location

Path
----
H:\src\t

PS 09:02 \\SRV1\SH1\home\pwatson2 H:\src\t

>Write-Host ([Environment]::CurrentDirectory)
C:\Windows\System32\WindowsPowerShell\v1.0
Related