2017-05-24 190 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中有效。这似乎是控制台和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对象' 。正如提交者所示,'Get-Location'返回的位置:'H:\ src \ powershell'与错误消息“C:\ src \ powershell \ ex.txt”中的位置不匹配 – BenH