3

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.

lit
  • 14,456
  • 10
  • 65
  • 119
  • Possible duplicate of [Why don't .NET objects in PowerShell use the current directory?](https://stackoverflow.com/questions/11246068/why-dont-net-objects-in-powershell-use-the-current-directory) – BenH May 24 '17 at 15:54

3 Answers3

1
Push-Location -Path $(Split-Path -Parent $myInvocation.MyCommand.Path)
$myInvocation.MyCommand.Path
Get-Location
$file = Resolve-Path '.\ex.txt'
$reader = New-Object System.IO.StreamReader($file)
rawel
  • 2,923
  • 21
  • 33
  • This is exactly what does not work in the Console host. Were you running this in ISE? – lit May 24 '17 at 20:46
  • I was running this on both ISE and console host. My environment is windows 10 though. Check `[Environment]::CurrentDirectory` environment variable. It might be set differently in console host and ISE – rawel May 24 '17 at 23:16
1

Just use:

Push-Location $PSScriptRoot

It will work in both cases as long as you're using a recent PowerShell version (v3+).

Pang
  • 9,564
  • 146
  • 81
  • 122
Maciej
  • 21
  • 2
  • This is incorrect, the issue is not with `$myInvocation.MyCommand.Path` but with creating a .Net object with `New-Object System.IO.StreamReader($file)`. As the asker shows, the location returned by `Get-Location` : `H:\src\powershell` does not match the location in the error message `'C:\src\powershell\ex.txt'` – BenH May 24 '17 at 17:13
1

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
lit
  • 14,456
  • 10
  • 65
  • 119