2017-05-24 18 views
1

このコードをISEで実行すると動作します。現在のディレクトリは明らかに現在のディレクトリではありません

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

コンソールで同じコードを実行するとエラーが発生します。私は何が欠けていますか?これは提案重複

他の質問/答えは異なっている方法

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 

は、PowerShellは、この場合には失敗した理由の説明を与えません。しかし、ISEでなぜこれが機能するのかについてのヒントはありません。これは、ConsoleとISEホストの間に大きな違いがあるようです。

Windows 7 Enterprise SP1でPSVersion 5.0.10586.117を実行しています。

+0

[PowerShellの.NETオブジェクトで現在のディレクトリが使用されないのはなぜですか?](https://stackoverflow.com/questions/11246068/why-dont-net-objects-in-powershell-use-the -current-directory) – BenH

答えて

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) 
+0

これはコンソールホストでは正しく動作しません。 ISEでこれを実行していましたか? – lit

+0

私はISEとコンソールホストの両方でこれを実行していました。私の環境はWindows 10です。 '[Environment] :: CurrentDirectory'環境変数を確認してください。コンソールホストとISEの設定が異なるかもしれません – rawel

0

だけ使用します。

Push-Location $PSScriptRoot 

それは限り、あなたは、最近のPowerShellのバージョン(V3 +)を使用しているとして、両方のケースで動作します。

+0

これは間違っています。問題は '$ myInvocation.MyCommand.Path'ではなく、' New-Object System.IO.StreamReader($ file) 'で.Netオブジェクトを作成することです。 。 Askerが示すように、 'Get-Location':' H:\ src \ powershell'で返された場所は、 'C:\ src \ powershell \ ex.txt'というエラーメッセージの場所と一致しません – BenH

関連する問題